Search code examples
c#pointerspinvokeintptr

Get pointer to unmanaged memory in C# from C++


I've been given a C++ DLL that allocates memory. It has several functions that need me to pass it the pointer to this allocated memory. I'm working in C# so I need to keep this pointer around, so I can pass it back to the C++ DLL when needed. The pointer will never be used in the C# side other than keeping it around to pass to the C++ code.

I'd prefer not to use the unsafe keyword at all.

I've created an IntPtr to pass to the C++ functions to store the allocated memory address, but it crashes immediately on the C++ side (AccessViolationException). I'm not sure of the proper syntax for the DLL call.

This is an example of what I'm trying to do:

[DllImport("data_accessor.dll")]
public static extern void get_pointer_to_new_memory(IntPtr memory_ptr);

Is this possible without using unsafe? If so, how?

UPDATE: Sorry I didn't post this sooner. Here is the function I'm calling. (Names have been changed to protect the innocent.)

typedef void* handle_ptr;
void DLL_API get_pointer_to_new_memory(handle_ptr* handle)

Solution

  • Thanks to Lucas' comment I got it working. I was on the right track...just missing the out keyword.

    [DllImport("data_accessor.dll")]
    public static extern void get_pointer_to_new_memory(out IntPtr memory_ptr);