使用DllImport调用c++函数
本文关键字:函数 c++ 调用 DllImport 使用 | 更新日期: 2023-09-27 18:12:47
这是基本的,我如何从c# DllImport调用函数SubscribeNewsFeed ?
class LogAppender : public L_Append
{
public:
LogAppender()
: outfile("TestLog.txt", std::ios::trunc | std::ios::out)
, feedSubscribed(false)
{
outfile.setf(0, std::ios::floatfield);
outfile.precision(4);
}
void SubscribeNewsFeed()
{
someOtherCalls();
}
};
我无法弄清楚如何在我的c#程序中使用DllImport时包含类名:
class Program
{
[DllImport("LogAppender.dll")]
public static extern void SubscribeNewsFeed();
static void Main(string[] args)
{
SubscribeNewsFeed();
}
}
PInvoke不能以这种方式直接调用c++函数。相反,您需要定义一个调用PInvoke函数的extern "C"
函数,并将PInvoke调用到该函数中。此外,您不能PInvoke到类实例方法中。
extern "C" void SubscribeNewsFeedHelper() {
LogAppender appender;
appender.SubscribeNewsFeed();
}
c# [DllImport("LogAppender.dll")]
public static extern void SubscribeNewsFeedHelper();
p/Invoke不是这样工作的。它只能导入C函数。因此,托管(c#)和本地(c++)世界之间存在不同类型的互操作。通过COM进行互操作将是一个解决方案——另外提供一个C接口。