1

I just created an unmanaged C++ DLL and am trying to use DllImport in my C# app to access the function calls. However, each function belongs to its own namespace (there are multiple header files, multiple namespaces, multiple class files). When I try calling the function DllImport it says the entry point can't be found, and I can't help but feel it has to do with namespaces. How do I call my functions using their unique namespaces? Thanks.

Nickersoft
  • 684
  • 1
  • 12
  • 30

4 Answers4

3

If you want to check the exported names of your functions you can use:

dumpbin /exports my_native_lib.dll

If it does not display any exports, there is something wrong with the way the functions are exported and we'll need more code.

Pragmateek
  • 13,174
  • 9
  • 74
  • 108
2

DllImport will work for 'global' C functions, not C++ classes - for C++ classes you'll have to create C wrappers for the functions you need. See: using a class defined in a c++ dll in c# code

Community
  • 1
  • 1
Dave Doknjas
  • 6,394
  • 1
  • 15
  • 28
1

you can use dependency walker to see the exported functions names of any dll. this way you could call on mangled function names.

geva30
  • 325
  • 2
  • 7
0

The answer is yes in VS 2022, I did not check earlier version. Sorry if this is late.

I used this construct for C# to access a public static method of a class within a namespace.

namespace LifetimeCallsCs {
internal sealed class NativeSimple {
    private NativeSimple() { }
    [DllImport("CppTransforms.dll", EntryPoint = "?LifetimeTransformCreate@LifetimeTransform@SimpleNS@@SAXPEAPEAX@Z", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, SetLastError = false)]
    public static unsafe extern void* LifetimeTransformCreate(void** handle);
    [DllImport("CppTransforms.dll", EntryPoint = "?LifetimeTransformDelete@LifetimeTransform@SimpleNS@@SAXPEAX@Z", CallingConvention = CallingConvention.Cdecl, ExactSpelling = true, SetLastError = false)]
    public static unsafe extern void LifetimeTransformDelete([In] IntPtr handle);
}

}

The argument EntryPoint = "...." specified the mangled method call.

the include file for c++ is:

namespace SimpleNS {

class LifetimeTransform
{
public:
    static void __declspec(dllexport) _cdecl LifetimeTransformCreate(void** handle);
    static void __declspec(dllexport) _cdecl LifetimeTransformDelete(void* handle);
};

}

The C++ code is:

namespace SimpleNS {
void LifetimeTransform::LifetimeTransformCreate(void** handle) {
    *handle = new SimpleNS::LifetimeTransformImp();
}
void LifetimeTransform::LifetimeTransformDelete(void* handle) {
    if (handle != nullptr)
        delete (SimpleNS::LifetimeTransformImp*)handle;
}

}

you can use dependency walker to see the exported functions names of any dll. this way you could call on mangled function names.

user3097514
  • 319
  • 2
  • 6