Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# DLLImport for C++ dll

I have a .dll built in C++/CLI and .NET. Therefore, it is targeted to .NET applications. The API is a set of wrappers that uses managed types so it is NET native. I have imported the .dll and added a function like:

[DllImport(@"maplib.dll")]
public static extern bool initialize(string a);

When I call this function in my C# code, it works fine, but if I want to add another function, like..

[DllImport(@"maplib.dll")]
public static extern bool initialize(string a);
public static extern bool runfile(string a, string b);

I get this error when I run my program. It is related to the second function:

"Could not load type 'myapp.main' from assembly 'myapp, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' because the method 'runfile' has no implementation (no RVA)."

Why does this error occur and how can I fix it?

like image 318
rayanisran Avatar asked Dec 02 '22 01:12

rayanisran


2 Answers

You must add the DllImport attribute twice if you want two functions:

[DllImport(@"maplib.dll")]
public static extern bool initialize(string a);
[DllImport(@"maplib.dll")]
public static extern bool runfile(string a, string b);

But if your dll is .NET then why not just add a regular reference to it and use it like you would use C# code?

like image 148
Scott Avatar answered Dec 05 '22 16:12

Scott


As I understand it, you have created a library of managed class(es) implemented in C++. You want to use this class library (assembly) in other managed code (written in C#, VB.NET, etc.). Currently, you have exported some methods (your API) as native C++ calls:

public bool initialize(string a) {
    // ...
}

public bool runfile(string a, string b) {
    // ...
}

This is useful if you want to be able to call your library from native C++ code, but if you want to use only managed code to call your library, I suggest that you create your API as managed code:

public ref class MyLibraryFunctions {
    public:
        static bool initialize(string a);
        static bool runfile(string a, string b);
};

This way, you do not need DllImport in your C# code. You can just do:

using Something.MyLibrary;
....
    public void doSomethingThatNeedsMyLibrary() {
       MyLibraryFunctions.initialize(someString);
    }

I hope I understood your question correctly.

like image 26
Krumelur Avatar answered Dec 05 '22 16:12

Krumelur