从C++/CLI调用C#dll函数
问题描述:
我有一个C#
dll。代码如下:从C++/CLI调用C#dll函数
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。
[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
private: System::Void CalculateResult(int arg1, int arg2)
{
int rez=0;
//Call C++ function from dll
Calculate calculate=new Calculate();
rez=GetResult(arg1,arg2);
}
我得到了错误: “语法错误:标识符 '计算'”。 有人可以帮助我解决这个可怕的错误吗?
答
您必须使用C++ CLI,否则您无法调用DllImport。 如果是这种情况,你可以参考c#dll。
在C++ CLI中,您可以做如下:
using namespace Your::Namespace::Here;
#using <YourDll.dll>
YourManagedClass^ pInstance = gcnew YourManagedClass();
其中 'YourManagedClass' 与输出组件的C#项目定义 'YourDll.dll'。编辑** 添加您的示例。
这就是你们的榜样需要怎么看起来像在CLI(为清楚起见,我假定使得G etResult不是一个静态的功能,否则你只需调用计算::调用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#程序集呢? DllImport是为了让你可以从托管代码中调用非托管dll, – santiagoIT 2011-01-27 15:18:49
我有点困惑于Visual Studio C++。我的DLL正确地在VS2010 C++项目中,我用Assembly.LoadFile尝试了没有任何成功。 – 2011-01-27 15:24:51