M
mczard
The MSDN documentation explains how to pass structures from C# to C
functions, but I can't find any help on how to return a structure by
value from C to C#. I don't want to return a pointer to the structure,
because it would require additional memory management.
I tried this:
------------------------------------------------------------------------
C:
struct Point
{
int x;
int y;
};
extern "C"
__declspec(dllexport)
Point proc3()
{
Point p;
p.x = 3;
p.y = 4;
return p;
}
------------------------------------------------------------------------
C#:
delegate Point Proc3();
....
IntPtr lib = LoadLibrary("../../../debug/CeeLibrary.dll");
IntPtr proc3 = GetProcAddress(lib, "proc3");
Proc3 del3 = (Proc3)Marshal.GetDelegateForFunctionPointer(proc3,
typeof(Proc3));
Point p3 = del3();
------------------------------------------------------------------------
and it does work, but it crashes if I add an integer parameter:
------------------------------------------------------------------------
C:
extern "C"
__declspec(dllexport)
Point proc4(int x)
{
Point p;
p.x = x;
p.y = 4;
return p;
}
------------------------------------------------------------------------
C#:
delegate Point Proc4(int x);
....
IntPtr lib = LoadLibrary("../../../debug/CeeLibrary.dll");
IntPtr proc4 = GetProcAddress(lib, "proc4");
Proc4 del4 = (Proc4)Marshal.GetDelegateForFunctionPointer(proc4,
typeof(Proc4));
Point p4 = del4(10);
functions, but I can't find any help on how to return a structure by
value from C to C#. I don't want to return a pointer to the structure,
because it would require additional memory management.
I tried this:
------------------------------------------------------------------------
C:
struct Point
{
int x;
int y;
};
extern "C"
__declspec(dllexport)
Point proc3()
{
Point p;
p.x = 3;
p.y = 4;
return p;
}
------------------------------------------------------------------------
C#:
delegate Point Proc3();
....
IntPtr lib = LoadLibrary("../../../debug/CeeLibrary.dll");
IntPtr proc3 = GetProcAddress(lib, "proc3");
Proc3 del3 = (Proc3)Marshal.GetDelegateForFunctionPointer(proc3,
typeof(Proc3));
Point p3 = del3();
------------------------------------------------------------------------
and it does work, but it crashes if I add an integer parameter:
------------------------------------------------------------------------
C:
extern "C"
__declspec(dllexport)
Point proc4(int x)
{
Point p;
p.x = x;
p.y = 4;
return p;
}
------------------------------------------------------------------------
C#:
delegate Point Proc4(int x);
....
IntPtr lib = LoadLibrary("../../../debug/CeeLibrary.dll");
IntPtr proc4 = GetProcAddress(lib, "proc4");
Proc4 del4 = (Proc4)Marshal.GetDelegateForFunctionPointer(proc4,
typeof(Proc4));
Point p4 = del4(10);