简体   繁体   English

从C#调用托管C ++时发生编译错误

[英]Compile error when calling managed C++ from C#

I am new to .net . 我是.net的新手。 I have a managed C++ library. 我有一个托管的C ++库。 It looks like this. 看起来像这样。

// header file
namespace cppnetdll
{
public __gc class Class1
{
public:
static int foo_int(void);
};
}

// source file
namespace cppnetdll
{
int Class1::foo_int(void)
{
return 123;
}
}

I can call this from a managed c++ program. 我可以从托管的c ++程序中调用它。 When I try to call it from a C# program, I get the compiler error: "The type or namespace name 'Class1' could not be found (are you missing a using directive or an assembly reference?)" The error refers to the DllImport line below. 当我尝试从C#程序调用它时,出现编译器错误:“找不到类型或名称空间名称'Class1'(您是否缺少using指令或程序集引用?)”该错误涉及DllImport下面的行。

Here is the C# code [code:1:a72c1df571] namespace csuser { public class xxx { [DllImport("cppnetdll.dll")] extern int Class1.foo_int(); 这是C#代码[code:1:a72c1df571]命名空间csuser {公共类xxx {[DllImport(“ cppnetdll.dll”)] extern int Class1.foo_int();

private void yyy() { int i =
foo_int(); }
}
}[/code:1:a72c1df571]

I have tried various approaches but no success. 我尝试了各种方法,但没有成功。 What is the magic syntax ? 什么是魔术语法?

It's funny that I can call unmanaged C++ functions from C# fairly easily by declaring the functions as "C" and exporting from the DLL. 有趣的是,通过将函数声明为“ C”并从DLL导出,可以相当容易地从C#调用非托管C ++函数。 I expected calling managed code to be easier. 我希望调用托管代码会更容易。 Maybe it's so easy that no one thought of documenting it ! 也许是如此简单,以至于没有人想到记录它!

You do not use a [DllImport] directive to call code that's written in managed C++. 您不使用[DllImport]指令来调用用托管C ++编写的代码。 That is only intended for native DLLs that export their functions. 这仅适用于导出其功能的本机DLL。 Neither of which applies to yours, it isn't native and you don't export the function. 两者都不适用于您,这不是本机的,并且您不导出函数。

You built a managed assembly, you can treat it just like one you'd have written in C#. 您建立了一个托管程序集,就可以像使用C#编写的程序集一样对待它。 Project + Add Reference, Browse tab, navigate to the DLL. 在“项目+添加引用”的“浏览”选项卡上,导航到DLL。 Or better yet, put both projects in one solution, use the Projects tab to select the reference. 或者更好的是,将两个项目都放在一个解决方案中,使用“项目”选项卡选择参考。

Instead of using the [DllImport ...] 代替使用[DllImport ...]

Try just adding a reference, here is a how to from MSDN: http://msdn.microsoft.com/en-us/library/7314433t%28v=VS.90%29.aspx 尝试仅添加参考,这是来自MSDN的方法: http : //msdn.microsoft.com/zh-cn/library/7314433t%28v=VS.90%29.aspx

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM