None

None

  • NA
  • 1
  • 0

Struct parameter c# to c++

Jun 14 2010 5:18 AM
I want to call a function from a c++ dll that accepts a struct as parameter in my c# code.
#include <iostream>
#include <cstring>
#define _e extern "C" __declspec(dllexport)
#define _i extern "C" __declspec(dllimport)

struct Args {
  std::string ip;
  std::string uparams;
};
_e std::string PAGE(Args args)
{
    std::string arguments = args.uparams;
    std::string buffer = "Hello World!!! <<--->> arguments -> \"";
    buffer += arguments;
    buffer += "\"";
    return buffer;
}
C# code
         [DllImport("kernel32.dll", EntryPoint = "LoadLibrary")]
        static extern int LoadLibrary(
            [MarshalAs(UnmanagedType.LPStr)] string lpLibFileName);

        [DllImport("kernel32.dll", EntryPoint = "GetProcAddress")]
        static extern IntPtr GetProcAddress(int hModule,
            [MarshalAs(UnmanagedType.LPStr)] string lpProcName);

        [DllImport("kernel32.dll", EntryPoint = "FreeLibrary")]
        static extern bool FreeLibrary(int hModule);

        struct Arguments
        {
            public string ip;
            public string uparams;
        };
        delegate string Str([MarshalAs(UnmanagedType.Struct)] Arguments args);
        static void Main(string[] args)
        {
            int a = LoadLibrary("C:\\CTEST.dll");
            if (a < 1) {
                Console.Write("Cannot load library");
                Console.Read();
                return;
            }
            Console.WriteLine("Library Loaded");
            Console.Read();
            Str st = (Str)Marshal.GetDelegateForFunctionPointer(GetProcAddress(a, "PAGE"), typeof(Str));
            Arguments ar;
            ar.ip = "127.0.0.1";
            ar.uparams = "Hell Yeah";
            Console.WriteLine(st(ar));
            FreeLibrary(a);
        }
But i get the folowing error when i call st() function 
Attempted to read or write protected memory. This is often an indication that other memory is corrupt

L.E Sorry for the bad section of my other thread.

Answers (1)