How to call C function from C # with WCHAR * out parameter?

I have problems with marshaling, and I just can't figure it out myself. I searched for this topic, but I have not succeeded yet, so basically I'm trying to call an unmanaged C function from my managed C # application. The signature of the C function looks like this:

long MyFunction(WCHAR* upn, long upnSize, WCHAR* guid, long* guidSize);

I don’t have access to the DLL file, I just know that the function is exposed for use, and I know what the function should do, but I don’t know what happens inside, so the function gets WCHAR * upn with the name UserPricipalName and the length of the incoming UPN. A WCHAR pointer is also passed, where the function writes back the corresponding GUID that is associated with the passed UPN. The guidSize pointer provides the size of the pointer; if it is too small, the written GUID is not completely written. If everything goes fine, the function should return 0 (this has not happened yet when called from C #)

Now my attempts to call and call this function are as follows:

[DllImport(@"MyDll.dll", EntryPoint = "MyFunction", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
public static extern long MyFunction(IntPtr upnPtr, long upnSize, [Out, MarshalAsAttribute(UnmanagedType.LPWStr) ] StringBuilder guidPtr, IntPtr guidSizePtr);


//my attempt to call the Dll exposed function
string upn = foo@bar.com;
long upnSize = upn.Length;
IntPtr upnPtr = Marshal.StringToHGlobalUni(upn);

IntPtr guidSizePtr = Marshal.AllocHGlobal(sizeof(long));
Marshal.WriteInt32(GuidSizePtr, 128);
var guidSB = new StringBuilder(128);

result = MyFunction(upnPtr, upnSize, guidSB, guidSizePtr);

AccessViolationException. , 0 , GUID, .

.

+5
1

:

    [DllImport(@"MyDll.dll", EntryPoint = "MyFunction", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Unicode)]
    public static extern int MyFunction([MarshalAsAttribute(UnmanagedType.LPWStr)] string upnPtr, int upnSize, [MarshalAsAttribute(UnmanagedType.LPWStr)] StringBuilder guidPtr, ref int guidSizePtr);

:

        string upn = "foo@bar.com";
        var guidSB = new StringBuilder(128);
        int guidSizePtr =guidSB.Capacity;
        MyFunction(upn, upn.Length, guidSB, ref guidSizePtr);

: ++ 32-, , int #.

+8

All Articles