2011-02-03 95 views

回答

2
[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); 
+0

然后使用`ToPointer()`方法来获得`void *`指针,然后可以将其转换为`int *`并取消引用。 – 2011-02-03 15:26:31

+0

嗨伙计,感谢您的回复,我使用以下代码段进行基于您的答复的指针转换。请告诉我,如果我错了。 Apolozose任何愚蠢的错误,即时通讯新手在C#和C++/CLI编程。 int b = 3; IntPtr errno = new IntPtr(&b); int * var =(int *)Marshal :: AllocHGlobal(errno).ToPointer(); – Ashutosh 2011-02-04 12:11:58

5

它是通过引用传递值的C/C++方式。您应该使用裁判关键字:

[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.. 
}; 
相关问题