我打算從 c# 呼叫 c 庫中的非托管函式,但它崩潰了。在進行故障排除時,我將其范圍縮小到 std::wstring。一個最小的示例如下所示:
C
#include <iostream>
extern "C" __declspec(dllexport) int __cdecl Start()
{
std::wstring test = std::wstring(L"Hello World");
return 2;
}
C#
using System.Runtime.InteropServices;
internal class Program
{
[DllImport("test.exe", CallingConvention=CallingConvention.Cdecl)]
public static extern int Start();
static void Main(string[] args)
{
var result = Start();
Console.WriteLine($"Result: {result}");
}
}
這給了我一個堆疊溢位。如果我洗掉該行std::wstring或將其更改為std::string,則沒有問題,我會回傳 2。
誰能向我解釋這里發生了什么?
uj5u.com熱心網友回復:
這是我注意到的:
[DllImport("test.exe", CallingConvention=CallingConvention.Cdecl)]
從 EXE 而不是 DLL 匯出函式不是標準的。(我認為可以做到,但我不建議這樣做。)
將您的 C 代碼構建為 DLL 而不是 EXE。將 DLL 與 C 運行時庫靜態鏈接,以避免由于加載程式搜索路徑中沒有正確的 DLL 而導致的丟失依賴問題。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/441484.html
