Search code examples
c#pinvoke

Trying to marshal C++ pointer to unsigned long into a C# ulong


I have a C++ DLL that I am trying to interface with using C#. I do not have access to the DLL source code so it cannot be changed. One of the methods I need to call contains a pointer to an unsigned long:

int __stdcall Foo(FooHandle messageHandle, unsigned long* tag, char* part, char* value)

I have created a test DLL project with the same method signature so I can try to figure this out but I have not successfully been able to have the DLL change the value of the unsigned long that the pointer is referencing and get that value back on the C# side. The C# side declaration is:

[DllImport("Foo.dll", EntryPoint = "Foo", CallingConvention = CallingConvention.StdCall)]
    public static extern int Foo(int messageHandle, IntPtr tag, StringBuilder part, StringBuilder value);

When I make the call from C# and then try to convert the IntPtr to Int32 or Int64 I get a zero. I have searched on here and the net in general as well as MSDN and can't seem to find an explaination of how to do this. I figured the char* would be the hard part but the StringBuilder just works.

How can you use a C++ DLL that changes the value of an unsigned long that is passed by pointer?

Any help would be appreciated. Thanks.


Solution

  • Just use a uint passed by ref:

    public static extern int Foo(int messageHandle, ref uint tag, StringBuilder part, StringBuilder value);