简体   繁体   中英

P/Invoke Return void*

I have a C function with the following signature:

int __declspec(dllexport) __cdecl test(void* p);

The function implementation is as following:

int i = 9;

int test(void* p)
{
    p = &i;
    return 0;
}

From a C# application, i want to return the value of the reference through the pointer to the C# application, so i did the following:

[DllImport(@"lib\test.dll", CallingConvention=CallingConvention.Cdecl)]
public static extern int test(out IntPtr p);

IntPtr p = IntPtr.Zero;

test(out p);

However, p does not have any value back.

Any help please!!

If you want to change the value of the caller's pointer argument, you need to pass a pointer to a pointer:

int test(void** p)
{
    *p = &i;
    return 0;
}

calling from C# something like

[DllImport(@"lib\test.dll", CallingConvention=CallingConvention.Cdecl)]
public static extern unsafe int test(IntPtr* p);

public unsafe void DotNetFunc()
{
    IntPtr p;
    test(&p);

If you don't like the use of unsafe , you could change your C function to return a pointer instead, returning NULL to indicate an error if necessary.

int* test()
{
    return &i;
}

[DllImport(@"lib\test.dll", CallingConvention=CallingConvention.Cdecl)]
public static extern IntPtr test();

IntPtr p = test();
if (p == IntPtr.Zero)
    // error

You don't need unsafe code. But you do need to fix the C code. Like so:

void test(int** p)
{
    *p = &i;
}

And the C# code is:

[DllImport("...", , CallingConvention=CallingConvention.Cdecl)]
static extern void test(out IntPtr p);

Call it like this:

IntPtr p;
test(out p);

And read the value like this:

int i = Marshal.ReadInt32(p);

Or return the pointer as the function return value:

int* test(void)
{
    return &i;
}

And in C#:

[DllImport("...", , CallingConvention=CallingConvention.Cdecl)]
static extern IntPtr test();

And I'm sure you can do the rest.

Try using pointer of pointer

int test(void** p)
{
    *p = &i;
    return 0;
}

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