簡體   English   中英

Marshaling從C ++ dll導出字符串向量

[英]Marshaling exported string vector from C++ dll

您如何封送從C ++ dll導出的字符串向量? 我想在將它們用於我的C#程序之前將它們分開。 你能救我嗎?

是。 您可以。 實際上,不僅是std::vectorstd::stringstd::wstring ,任何標准C ++類或您自己的類都可以編組或實例化,並從C#/ .NET調用。

僅使用常規P / Invoke Interop確實可以在C#中包裝std::vector<any_type> ,但這很復雜。 甚至任何類型的std :: map都可以在C#/。NET中完成。

從.NET世界實例化C ++對象的基本思想是從.NET分配C ++對象的確切大小,然后調用從C ++ DLL導出的構造函數來初始化對象,然后你就可以調用任何一個訪問該C ++對象的函數,如果任何方法涉及其他C ++類,您還需要將它們包裝在C#類中,對於具有基本類型的方法,您可以簡單地P / Invoke它們。 如果只有幾種方法可以調用,則很簡單,手動編碼不會花費很長時間。 完成C ++對象后,您將調用C ++對象的destructor方法,該方法也是一個導出函數。 如果沒有,則只需要從.NET中釋放內存即可。

這是一個例子。

public class SampleClass : IDisposable
{    
    [DllImport("YourDll.dll", EntryPoint="ConstructorOfYourClass", CharSet=CharSet.Ansi,          CallingConvention=CallingConvention.ThisCall)]
    public extern static void SampleClassConstructor(IntPtr thisObject);

    [DllImport("YourDll.dll", EntryPoint="DoSomething", CharSet=CharSet.Ansi,      CallingConvention=CallingConvention.ThisCall)]
    public extern static void DoSomething(IntPtr thisObject);

    [DllImport("YourDll.dll", EntryPoint="DoSomethingElse", CharSet=CharSet.Ansi,      CallingConvention=CallingConvention.ThisCall)]
    public extern static void DoSomething(IntPtr thisObject, int x);

    IntPtr ptr;

    public SampleClass(int sizeOfYourCppClass)
    {
        this.ptr = Marshal.AllocHGlobal(sizeOfYourCppClass);
        SampleClassConstructor(this.ptr);  
    }

    public void DoSomething()
    {
        DoSomething(this.ptr);
    }

    public void DoSomethingElse(int x)
    {
        DoSomethingElse(this.ptr, x);
    }

    public void Dispose()
    {
        Marshal.FreeHGlobal(this.ptr);
    }
}

有關詳細信息,請參閱以下鏈接,

C#/。NET PInvoke Interop SDK

(我是SDK工具的作者)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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