簡體   English   中英

如何從C#代碼內部調用C ++ DLL中定義的,具有int *類型參數的函數?

[英]How do I call a function defined in a C++ DLL that has a parameter of type int *, from inside C# code?

我有一個本地常規C ++ Dll,我想從C#代碼中調用,因此我創建了C ++ / CLI類(如此此處所述 ),其中將包括托管C ++代碼,並且可以由任何C#代碼直接調用,並且可以調用本身的非托管C ++。

本機C ++ dll中的功能之一具有int *類型的參數。 如何在包裝函數中聲明,如何將其轉換為int *?

這是通過引用傳遞值的C / C ++方法。 您應該使用refout關鍵字:

[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.

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