Problem with Interop C # / C: AccessViolationException

and thanks for the consultation for any help.

i has this trivial function in C:

__declspec(dllexport)  Point* createPoint (int x, int y) {
    Point *p;

    p = (Point*) malloc(sizeof(Point)); 
    p->x = x;
    p->y=y;

    return p;       
}

A dot is a very simple structure with two int fields, x and y.

I would like to call this function from C #.

I am using this code:

[DllImport("simpleC.dll", EntryPoint = "createPoint", CallingConvention = CallingConvention.Cdecl, SetLastError = true, CharSet = CharSet.Auto)]
[return: MarshalAs(UnmanagedType.LPStruct)]
public static extern Point createPoint(int x, int y);

Point p = Wrapper.createPoint(1, 2);

But at runtime I have AccessViolationException. Watching the exception in detail, I found that the exception was thrown from the method Marshal.CoTaskMemFree(IntPtr).

It seems that this method cannot free the memory allocated by C malloc.

What am I doing wrong?

Thanks a lot.

+3
source share
3 answers

CoTaskMemFree , malloc ( ). MSDN, "runtime CoTaskMemFree . , , CoTaskMemAlloc , IntPtr ."

, , "UnmanagedType.LPStruct : System.Guid GUID ... , , UnmanagedType.LPStruct."

:

: SetLastError Win32 API, SetLastError = true P/Invoke .

+2

, "p", . , , malloc() free() , , # . # ( ), , .

, , . "destroyPoint", C, # , C.

/ "create" "free/destroy/delete". , , .

+1

How is the point type defined on the C # side?
It must be unsafe, or you need to return a pointer to the void (IntPtr). GC cannot count links from outside (allocated memory here), so your code cannot count on managing external allocated memory through GC.
An alternative is to keep a static link to avoid garbage collection if you need to permanently save the object while your application is running.

+1
source

Source: https://habr.com/ru/post/1780839/


All Articles