0

All in the title really. I have a library, written in c++ and compiled into a dll. I would like to use this functionality in a c# program. Is it possible to use the classes/functions from the library straight from c#, would I need to write some wrapper code to use it in a managed environment? Can they be used in an unsafe context? Sorry if this is a silly question - I'm a c++ programmer trying to move over to c#.

p.s. the library is from a third party, so I cannot port it direct to c# even if I had the time.

James Edge
  • 245
  • 5
  • 12
  • read [this SO q/a](http://stackoverflow.com/questions/8333159/exporting-c-code-as-a-dll-and-import-using-c) – jltrem Oct 02 '13 at 14:11

3 Answers3

2

It depends on how the C++ dll exports it's functionality.

If it's through C++ classes, then your best bet is to build a wrapper in C++/CLI that will consume the C++ classes and expose .NET classes to interact with them.

If it's through "classic" C-style functions, then you can use p-invoke to call the functions directly. It would be similar to the ways system DLLs like System32 and User32 are accessed.

D Stanley
  • 149,601
  • 11
  • 178
  • 240
1

Yes it's possible! First add the reference to System.Runtime.InteropServices:

using System.Runtime.InteropServices;

After you have to import the function on the external Dll:

    [DllImport("ExternalDLL.dll", EntryPoint = "FunctionNameOnExtDll")]
    public static extern CSharpDataType FunctionNameOnExtDll(ParameterDataType ParameterName);

And finally use it!!

FunctionNameOnExtDll(Parameter);
António Campos
  • 171
  • 2
  • 12
0

Yes it is possible, just knowing the signature of the functions you want to call and use System.Runtime.InteropServices facilities.
To help, use this tool PInvoke Interop Assistant that can help define data structures to be passed in calls.

lsalamon
  • 7,998
  • 6
  • 50
  • 63