问题描述
我有一个 C#
dll.代码如下:
I have a C#
dll. The code is below:
public class Calculate
{
public static int GetResult(int arg1, int arg2)
{
return arg1 + arg2;
}
public static string GetResult(string arg1, string arg2)
{
return arg1 + " " + arg2;
}
public static float GetResult(float arg1, float arg2)
{
return arg1 + arg2;
}
public Calculate()
{
}
}
现在,我打算以这种方式从 C++
调用这个 dll.
Now, I am planning to call this dll from C++
on this way.
[DllImport("CalculationC.dll",EntryPoint="Calculate", CallingConvention=CallingConvention::ThisCall)]
extern void Calculate();
[DllImport("CalculationC.dll",EntryPoint="GetResult", CallingConvention=CallingConvention::ThisCall)]
extern int GetResult(int arg1, int arg2);
这里是调用GetResult的函数
Here is function where is called GetResult
private: System::Void CalculateResult(int arg1, int arg2)
{
int rez=0;
//Call C++ function from dll
Calculate calculate=new Calculate();
rez=GetResult(arg1,arg2);
}
我收到错误消息:语法错误:标识符‘计算’".有人能帮我解决这个可怕的错误吗?
I got the error : "syntax error : identifier 'Calculate'".Can someone help me with this terrible error?
推荐答案
您必须使用 C++ CLI,否则无法调用 DllImport.如果是这种情况,您可以只引用 c# dll.
You must be using c++ CLI, otherwise you could not call DllImport.If that is the case you can just reference the c# dll.
在 C++ CLI 中,您可以执行以下操作:
In c++ CLI you can just do as follows:
using namespace Your::Namespace::Here;
#using <YourDll.dll>
YourManagedClass^ pInstance = gcnew YourManagedClass();
在带有输出程序集YourDll.dll"的 c# 项目中定义了YourManagedClass".
where 'YourManagedClass' is defined in the c# project with output assembly 'YourDll.dll'.
** 编辑 **添加了您的示例.
** EDIT **Added your example.
这就是您的示例在 CLI 中的外观(为清楚起见,我假设 GetResult 不是静态函数,否则你只需调用Calculate::GetResult(...)
This is how your example needs to look like in CLI (for clarity I am assuming that GetResult is not a static function, otherwise you would just call Calculate::GetResult(...)
private: System::Void CalculateResult(int arg1, int arg2)
{
int rez=0;
//Call C++ function from dll
Calculate^ calculate= gcnew Calculate();
rez=calculate->GetResult(arg1,arg2);
}
这篇关于从 C++/CLI 调用 C# dll 函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!