简体   繁体   中英

Compile error when calling managed C++ from C#

I am new to .net . I have a managed C++ library. 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. 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.

Here is the C# code [code:1:a72c1df571] namespace csuser { public class 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. 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++. That is only intended for native DLLs that export their functions. 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#. Project + Add Reference, Browse tab, navigate to the DLL. Or better yet, put both projects in one solution, use the Projects tab to select the reference.

Instead of using the [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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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