简体   繁体   中英

Using safe mode to get char** from dll (Passed as (IntPtr) parameter to the function)

I have a dll to which I pass a char** pointer: I can do that as following in VS 2010 c# unsafe mode:

public unsafe void loadParamListFromWks()
{
    char** list = null;
    dllFunctionGetList((IntPtr)(&list));

    int i = 0;
    IntPtr ptr;
    while ((ptr = (IntPtr)parameterNames[i]) != IntPtr.Zero)
    {
        Console.WriteLine(Marshal.PtrToStringAnsi(ptr));
        i++;
        ptr = (IntPtr)parameterNames[i];
    }
}  

As you see the dll populates an array of string (list) that I will use after in my code How can I do that in safe mode? I hope to get a short simple approach.

Try the below way, if you want to avoid unsafe .

Use DLL import attribute.

Use the namespace System.Runtime.InteropServices

Also for different calling conventions in DLL import attribute refer:

https://msdn.microsoft.com/en-us/library/system.runtime.interopservices.callingconvention(v=vs.110).aspx

(Rough code. Not tested)

//DECLARE THE FUNCTION FROM DLL
[DllImport(<<YOUR DLL>>,CallingConvention = CallingConvention.Cdecl, CharSet=CharSet.Ansi)]
public static extern void dllFunctionGetList(IntPtr[] ListOfStrs);

//GET THE LIST OF STRINGS
IntPtr[] parameterNames = new IntPtr[100];
dllFunctionGetList(parameterNames);

int i = 0;
IntPtr ptr;

//ITERATE THE STRINGS
while ((ptr = (IntPtr)parameterNames[i]) != IntPtr.Zero)
{
    Console.WriteLine(Marshal.PtrToStringAnsi(ptr));
    i++;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM