簡體   English   中英

從C#用LPStr返回值調用C ++函數

[英]Calling C++ function with LPStr return value from C#

我有一個64位的C ++ dll,其中包含一個返回LPStr的函數。 我想在C#中調用此函數。 函數聲明如下所示:

__declspec(dllexport) LPSTR __stdcall function(int16_t error_code);

在我的C#代碼中,我嘗試了以下操作:

 [DllImport(@"<PathToInterface.dll>", EntryPoint = "function")]
 [return: MarshalAs(UnmanagedType.LPStr)]
 public static extern string function(Int16 error_code);

然后在程序中:

string ErrorMessage = "";
ErrorMessage = function(-10210);

我知道函數本身很好,因為我可以從另一個程序(用LabVIEW FWIW編寫)中調用它。 但是,當我執行C#程序時,它以錯誤代碼0x80000003退出,我什至無法嘗試捕獲異常。

如何正確調用此功能?

作為副節點:我確實在此dll中還有其他函數,這些函數使用LPStr作為參數,可以毫無問題地調用它。 只有兩個返回LPStr函數會LPStr問題

如何正確調用此功能?

作為互操作? 您不能...在純C ++中它也容易出錯

你應該這樣做

extern "C" __declspec(dllexport)  int __stdcall function(int16_t error_code, 
             LPSTR buffer, size_t size)
{
    LPCSTR format = "error: %i";
    size_t req = _scprintf(format, error_code); // check for require size
    if (req > size) //buffer size is too small
    {
        return req; //return required size
    }
    sprintf_s(buffer, size, format, error_code); //fill buffer 
    return 0;
}

和用法

class Program
{
    static void Main(string[] args)
    {
        short error_code = -10210;
        var ret = function(error_code, null, 0); // check for required size of the buffer
        var sb = new StringBuilder(ret); // create large enough buffer
        ret = function(error_code, sb, (uint)sb.Capacity + 1); //call again 
        var error_desc = sb.ToString(); //get results
        Console.WriteLine(error_desc);
        Console.ReadKey();
    }

    [DllImport("TestDll.dll", EntryPoint = "function", CharSet = CharSet.Ansi)]
    public static extern int function(short error_code, StringBuilder sb, int size);
}

在C ++中的用法

typedef int (__stdcall *function)(int16_t error_code, LPSTR buffer, size_t size);
int main()
{
    auto handle = LoadLibrary(L"TestDll.dll");
    auto proc = (function)GetProcAddress(handle, "_function@12"); 
    // of course it can be done via linking

    int16_t error_code = 333;
    const int ret = proc(error_code, NULL, 0); // check for size
    CHAR* buffer = new CHAR[ret + 1];
    //CHAR buffer[200]; //eventually allocate on stack 
    //but size have to be constant value and may be too small
    proc(error_code, buffer, ret+1); // call again 
    MessageBoxA(0, buffer, "Return", 0); //show result
    delete[] buffer; //free buffer!

    FreeLibrary(handle);
    return 0;
}

暫無
暫無

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

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