2011-02-03 94 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.. 
}; 
相關問題