亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何通過 DllImport 將雙精度數組從 C# 傳遞到 C++

如何通過 DllImport 將雙精度數組從 C# 傳遞到 C++

C#
千巷貓影 2023-07-22 18:12:23
我有一個 C++ 函數,其方法簽名為MyMethod(std::vector<double> tissueData, std::vector<double> BGData, std::vector<double> TFData, std::vector<double> colMeans, std::vector<double> colStds, std::vector<double> model)我希望通過 dllimport 在 C# 中調用這個 C++ 函數。在創建 dll 庫時,我已將 C++ 端的函數定義為extern "C" __declspec(dllexport) int MyMethod(double *tissue, double *bg, double *tf, double *colMeans, double *colStds, double* model);我計劃將一個雙精度數組從 c# 端傳遞到 c++ dll 函數。但是,我不確定應該如何從 C# 端定義 DllImport 以及當我將其解析為 dllImport 函數時應該如何轉換雙精度數組?我讀了一些關于編組的內容,但我仍然不太明白,我不確定它是否可以應用在這里?
查看完整描述

1 回答

?
冉冉說

TA貢獻1877條經驗 獲得超1個贊

您不能與 C++ 類(例如std::vector)進行互操作,只能與基本的 C 樣式數據類型和指針進行互操作。(作為旁注)這是 Microsoft 在發明 COM 時試圖解決的問題之一。


為了使其工作,您應該導出一個不同的函數,該函數接收純 C 數組及其各自的長度:


C++端

extern "C" __declspec(dllexport) int MyExternMethod(

    double *tissue, int tissueLen, 

    double *bg, int bgLen,

    /* ... the rest ... */

);


// implementation

int MyExternMethod(

    double* tissue, int tissueLen, 

    double* bg, int bgLen,

    /* ... the rest ... */ )

{

    // call your original method from here:


    std::vector<double> tissueData(tissue, tissue + tissueLen);

    std::vector<double> bgData(bg, bg + bgLen);

    /* ... the rest ... */


    return MyMethod(tissueData, bgData, /* ...the rest... */);

}

C# 端的互操作導入為:


C#端

public static class MyLibMethods

{

    [DllImport("MyLib.dll", CallingConvention = CallingConvention.Cdecl)]

    public static extern int MyExternMethod(

        double[] tissue, int tissueLen,

        double[] bg, int bgLen,

        /*...the rest...*/

    );

}

你可以在 C# 中這樣調用它:


C#端

public int CallMyExternMethod(double[] tissue, double[] bg, /*... the rest ...*/)

{

    return MyLibMethods.MyExternMethod(

        tissue, tissue.Length,

        bg, bg.Length,

        /*...the rest...*/

    );

}


查看完整回答
反對 回復 2023-07-22
  • 1 回答
  • 0 關注
  • 187 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號