C# 从C调用非托管(C+;+;)函数时出现PInvoke错误# 我有一个未经编写的C++ DLL,我已经编写和测试过了。当在未配置的控制台应用程序中构建和运行时,未配置的代码工作正常。函数声明如下所示 #ifndef IMPORT_MYLIB # define MYLIB_API __declspec(dllexport) #else # define MYLIB_API __declspec(dllimport) #endif namespace gsod_data_parsing { extern "C" { MYLIB_API int parse_raw_gsod_file_nocb( const char *path, int temp_threshold ); } }
我正在尝试从托管应用程序调用它。我在我的C#文件中声明函数如下:C# 从C调用非托管(C+;+;)函数时出现PInvoke错误# 我有一个未经编写的C++ DLL,我已经编写和测试过了。当在未配置的控制台应用程序中构建和运行时,未配置的代码工作正常。函数声明如下所示 #ifndef IMPORT_MYLIB # define MYLIB_API __declspec(dllexport) #else # define MYLIB_API __declspec(dllimport) #endif namespace gsod_data_parsing { extern "C" { MYLIB_API int parse_raw_gsod_file_nocb( const char *path, int temp_threshold ); } },c#,c++,dll,pinvoke,marshalling,C#,C++,Dll,Pinvoke,Marshalling,我正在尝试从托管应用程序调用它。我在我的C#文件中声明函数如下: [DllImport("GSODDLL.dll")] public static extern int parse_raw_gsod_file_nocb( [MarshalAs(UnmanagedType.LPStr)] string path, int temp_threshold ); 然后,这些函数将在两个并行任务上执行,如下所示: // Start a task - this runs on the b
[DllImport("GSODDLL.dll")]
public static extern int parse_raw_gsod_file_nocb(
[MarshalAs(UnmanagedType.LPStr)] string path,
int temp_threshold
);
然后,这些函数将在两个并行任务上执行,如下所示:
// Start a task - this runs on the background thread...
task1 = Task.Factory.StartNew(() =>
{
int t1 = parse_raw_gsod_file_nocb(filePaths[i], this._frostTemp);
return (t1 == 0);
}, this._tokenSource.Token);
一开始它似乎运行得很好,但后来(我相信当函数完成执行时)我得到了以下错误
对PInvoke函数数据库的调用
造物主!Database_Creator.Form1::parse_raw_gsod_file_nocb'已
使堆栈不平衡。这可能是因为管理的PInvoke
签名与非托管目标签名不匹配。检查一下
PInvoke签名匹配的调用约定和参数
目标非托管签名
我看到了一个类似的问题,但我不太明白被接受的答案
有人有什么想法吗?
谢谢,原来我的问题是因为调用约定不匹配。根据这一点,windows中C/C++程序的默认调用约定是Cdecl。此外,根据这一点,PInvoke的默认调用约定是StdCall。我最初没有指定任何调用约定,因此默认为StdCall。由于这些约定指定了在函数调用后如何清理堆栈,因此在函数执行结束时抛出错误是有意义的 将我的PInvoke声明更改为此修复了我的问题:
[DllImport("GSODDLL.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int parse_raw_gsod_file_nocb(
[MarshalAs(UnmanagedType.LPStr)] string path,
int temp_threshold
);