[英]PInvoke with a void * versus a struct with an IntPtr
想象一下,我有一個叫做的函數
Myfunction(const void * x);
我的C#聲明可能是
MyFunction(IntPtr x);
這在功能和技術上是等同於
struct MyStruct { IntPtr P; }
MyFunction(MyStruct x);
或者他們的編組方式會有所不同。
我問這個是因為我正在調用的庫是無效的*,對其他名稱鍵入了類型,而在C#中我希望獲得類型安全性,因為它的價值。
如果您的StructLayout是Sequential,那么它確實是相同的。
最簡單的方法是自己驗證這個,當然是嘗試一下:
制作一個C ++ Win32 DLL項目:
extern "C"
{
__declspec(dllexport) void MyFunction(const void* ptr)
{
// put a breakpoint and inspect
}
}
制作一個C#項目:
public struct Foo
{
public IntPtr x;
}
[DllImport(@"Win32Project1.dll", EntryPoint = "MyFunction", CallingConvention = CallingConvention.Cdecl)]
public static extern void MyFunctionWithIntPtr(IntPtr x);
[DllImport(@"Win32Project1.dll", EntryPoint = "MyFunction", CallingConvention = CallingConvention.Cdecl)]
public static extern void MyFunctionWithStruct(Foo x);
static void Main(string[] args)
{
IntPtr j = new IntPtr(10);
var s = new Foo();
s.x = new IntPtr(10);
MyFunctionWithIntPtr(j);
MyFunctionWithStruct(s);
}
在調試設置中,確保選擇“啟用本機調試”。
你會看到兩個值都是0xA。
但是,請注意,如果對IntPtr vs Struct使用out / ref參數,它們將是不同的值。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.