簡體   English   中英

從 C# 程序訪問 C++ DLL

[英]Access C++ DLL from C# program

我對互操作很陌生,我在定義從 C++ DLL 導入的 dll 時遇到了問題。 DLL 的文檔如下:

bool __stdcall __declspec(dllexport) InitHW(char *name, char *model, int& type)

所以我嘗試的代碼如下,它給出了 system.AccessViolation 異常:

[DllImport("extIO_IC7610.dll", CallingConvention = CallingConvention.Cdecl)]
public unsafe static extern bool InitHW(string name, string model, int type);

private unsafe void Initialize()
{
    try
    {
        bool result;

        string name = "Test";
        string model = "Model";
        int type = 3;

        result = InitHW(name, model, type);
    }
    catch (Exception ex)
    {

    }
}

我剛剛意識到這應該返回數據。 有人可以在這里告訴我我理解中的錯誤嗎? 謝謝,湯姆

根據評論,我將內容更改為如下所示:

[DllImport("extIO_IC7610.dll", CallingConvention = CallingConvention.Cdecl)]
[return: MarshalAs(UnmanagedType.I1)] 
public unsafe static extern bool InitHW(string name, string model, ref int type);

unsafe private void Initialize())
{

    try
    {
        bool result;

        string name = ""; 
        string model = ""; 
        int type = 3;
        result = InitHW(name, model, ref type);

    }
    catch (Exception ex)
    {

    }
}

這仍然不起作用。 我現在收到一個錯誤,由於簽名不匹配,堆棧不平衡。 我認為字符串正確完成,但 &int 參數可能仍然是一個問題。 湯姆

嗯,我解決了。 這里有一些提示,但沒有什么是真正正確的。 在過去幾個小時環顧四周后,這是解決方案:

    [DllImport("extIO_IC7610.dll", CallingConvention = CallingConvention.StdCall, CharSet = CharSet.Ansi)]
    [return: MarshalAs(UnmanagedType.I1)] 
    public unsafe static extern bool InitHW(StringBuilder name,  StringBuilder model, int* type);

unsafe void Initialize()
{
           bool result;

            int type = 0;
            var name = new StringBuilder(250);
            var model = new StringBuilder(250);

            result = InitHW(name, model, &type);

            string _name = name.ToString();
            string _model = model.ToString();

}

暫無
暫無

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

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