Reputation: 273
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 !
Upvotes: 0
Views: 1042
Reputation: 942438
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.
Upvotes: 3
Reputation: 151
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
Upvotes: 1