2

My code works, but I am afraid of the memory within P/Invoke.

Here is the delegate I will call from native C++ code.

[UnmanagedFunctionPointer(CallingConvention.StdCall, CharSet = CharSet.Unicode)]
public delegate string CommandCallbackDelegate([MarshalAs(UnmanagedType.LPWStr)] string command
    , [MarshalAs(UnmanagedType.LPWStr)] string arg1
    , [MarshalAs(UnmanagedType.LPWStr)] string arg2
    );

And in C#, I passed the delegate to native DLL.

private static GCHandle _gcHandle;
public static void RegisterCommandCallback(CommandCallbackDelegate fun) { _gcHandle = GCHandle.Alloc(fun);

    if (IntPtr.Size == 8)
        RegisterCommandCallback_x64(fun);
    else
        RegisterCommandCallback_x86(fun);
}

And in the native DLL, after I get the function pointer, I can call the method successfully and get the returned String from C#.

typedef LPCWSTR (WINAPI* PFN_CommandCallback)( LPCWSTR wszCommand, LPCWSTR wszArg1, LPCWSTR wszArg2);
PFN_CommandCallback g_pfnCommandCallback = ....;

LPCWSTR wszRet = g_pfnCommandCallback( L"CMD", L"ARG1", L"ARG2");

As you can see, the C# method returns String to the native DLL, I am not sure if the returned unmanaged memory is repleased by GC.

Although my above code works, I am afraid it is accessing the memory which is just released.

1 Answer 1

1

In this situation, the pinvoke marshaller allocates the string return value with the shared COM allocator. So your native code should call CoTaskMemFree on the pointer that the native DLL returns. And so you may need to take a copy of the contents before you free the memory!

As an aside, there's no need to decorate the parameters with [MarshalAs(UnmanagedType.LPWStr)] since that just re-states the default. Your code would be easier to read with that removed.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.