简体   繁体   中英

Link .lib in Visual Studio dll project and export classes/functions

I have a visual studio project that outputs a static library and for my purposes I want to keep this project. But I also want a dll with many of the classes from the static lib exported so in a C# app I can import the dll and use the exported functions.

I've created a Console application with application type dll and I've referenced the lib. Everything seems to build just fine but when I run dumpbin on the dll there is nothing exported.

My question is how do I export the classes in the lib?

You'll need to use the _declspec(export) keyword on your class definition.

A lot of the time you'll see projects have a macro definition for it with some variant of:

#define DllExport __declspec( dllexport )

Here's an article from MSDN .

An example:

class __declspec( dllexport ) Foo
{
 // ...
};

Or

class DllExport Foo
{
  // ...
};

As has been said in another answer, you can export a C++ class from a DLL using __declspec , but it doesn't sound like that's what you need, as you say you want to use this library from C#, which doesn't understand C++ classes, and using P/Invoke will be awkward as the method names will be mangled.

Some simpler options for accessing C++ classes from C#:

  1. You could build your C++ library as a CLR class library, and wrap up your C++ classes with .NET classes, and then reference that class library in your C# project.

  2. You could use Swig to generate a C# wrapper around your C++ code.

  3. You could wrap up your C++ classes with a set of C functions that you can export from a DLL using __declspec(dllexport) , and call into from C# using P/Invoke.

If you really do want to export the C++ classes from the DLL though I'd suggest adding build configurations to your existing static library project, maybe called "DLL Debug" and "DLL Release", and change the settings for those build configurations to build as DLL, because it sounds like currently you're just linking a DLL against a static library, not exporting what's in the static library.

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