簡體   English   中英

P /調用返回無效*

[英]P/Invoke Return void*

我有一個帶有以下簽名的C函數:

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

函數實現如下:

int i = 9;

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

從C#應用程序,我想通過指向C#應用程序的指針返回引用的值,所以我做了以下工作:

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

IntPtr p = IntPtr.Zero;

test(out p);

但是,p沒有任何價值。

任何幫助,請!

如果要更改調用者的指針參數的值,則需要將指針傳遞給指針:

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

從C#調用類似

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

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

如果您不喜歡使用unsafe ,則可以更改C函數以改為返回指針,並在必要時返回NULL以指示錯誤。

int* test()
{
    return &i;
}

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

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

您不需要不安全的代碼。 但是您確實需要修復C代碼。 像這樣:

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

C#代碼是:

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

這樣稱呼它:

IntPtr p;
test(out p);

並讀取這樣的值:

int i = Marshal.ReadInt32(p);

或返回指針作為函數的返回值:

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

在C#中:

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

而且我相信您可以做剩下的事情。

嘗試使用指針的指針

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM