ezhang94
ezhang94

Reputation: 25

C# - Unable to Access Methods Included in C++/CLI .dll

I have two C++/CLI DLLs that I am trying to use with C#. I am using VS10 and have made sure that the DLLs are appropriately included in the "References" folder.

So, the first DLL works great. It contains classes, so the C# application can access the functions within the classes by 1) creating an instance of a class found in the DLL, then 2) calling the function "normally." (e.g. instanceOfClass.method1();).

The second DLL does not work. In the second DLL, all functions are at a global scope. No namespace scopes or classes. I am running into issues here, because when I try to access one of these functions in the C# application, I get an error: The name 'fxn' does not exist in the current context. I have tried all of the following possible ways of addressing the function:

namespace myDLL {           // Tried with and without namespace declaration
    class Program {
        static void Main(string[] args) {
            fxnInitialize();
            myDLL.fxnInitialize();
            myDLL->fxnInitialize();    
        }
    }
}

All of the other questions I have found regarding this issue have been with C++ DLLs with classes. My issue is: Is it possible to reference methods in DLLs that don't belong to a class?

Upvotes: 1

Views: 621

Answers (1)

Hans Passant
Hans Passant

Reputation: 941665

If it is not possible, why can't C# not use "class-less" DLLs?

Because the CLR does not support it, methods must always be a member of a class. That's an impedance mismatch with C++'s support for free functions. The C++/CLI compiler solves it by moving them into a class anyway. It's name is <Module> and it is not accessible outside of the assembly. Like an internal class in C#. In effect making the functions inaccessible as well.

Solving it is simple, add them to a ref class. You can declare them static.

Upvotes: 1

Related Questions