-2

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)
NielW
  • 3,626
  • 1
  • 30
  • 38
  • `IntPtr` is the way to go - and you don't need `unsafe` for that. As for your exception, make sure the function signatures match, **and** also make sure you're using the correct [calling convention](https://msdn.microsoft.com/en-us/library/system.runtime.interopservices.dllimportattribute.callingconvention.aspx). – Lucas Trzesniewski Feb 21 '15 at 00:40
  • 2
    Wait... given the name of the function from your example, I'd expect either `IntPtr get_pointer_to_new_memory()` or `void get_pointer_to_new_memory(out IntPtr memory_ptr)`. – Lucas Trzesniewski Feb 21 '15 at 00:44
  • 2
    Can you post the signature of the actual c++ function please –  Feb 21 '15 at 01:00
  • This kind of interop is all about matching two versions of a function. You only showed one. – David Heffernan Feb 21 '15 at 06:35

1 Answers1

0

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);
NielW
  • 3,626
  • 1
  • 30
  • 38