[英]How do I call a function in a C++ Dll from C# that has void* callback and object parameter
[英]How do I call a function defined in a C++ DLL that has a parameter of type int *, from inside C# code?
這是通過引用傳遞值的C / C ++方法。 您應該使用ref或out關鍵字:
[DllImport("something.dll")]
private static extern void Foo(ref int arg);
在C ++ / CLI中,大致如下所示:
public ref class Wrapper {
private:
Unmanaged* impl;
public:
void Foo(int% arg) { impl->Foo(&arg); }
// etc..
};
[DllImport("some.dll")]
static extern void SomeCPlusPlusFunction(IntPtr arg);
IntPtr是大致等於void *的類型。
從您的評論中,您最好關閉以下代碼(C#):
int size = 3;
fixed (int *p = &size) {
IntPtr data = Marshal.AllocHGlobal(new IntPtr(p));
// do some work with data
Marshal.FreeHGlobal(data); // have to free it
}
但是由於AllocHGlobal可以接受一個int,所以我不知道為什么你不這樣做:
IntPtr data = Marshal.AllocHGlobal(size);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.