Calling a C++ dll from C#

  • Thread starter Thread starter andanb
  • Start date Start date
A

andanb

Hi all,

I have been struggling with the following problem:
- How can I create a C++ dll in Microsoft Visual Studio?
- How can I call the dll from C#?

I would really appreciate your help!

Thanks,
An
 
I have been struggling with the following problem:
- How can I create a C++ dll in Microsoft Visual Studio?

Create a new project, making it a C++ DLL. You can make it "managed" or
"unmanaged". "Managed" is easier to use with C#, "unmanaged" allows the
DLL to be used outside of the .NET Framework environment.
- How can I call the dll from C#?

If you made a "managed" DLL, then you simply add the DLL as a reference to
your C# project.

If you made an "unmanaged" DLL, then you will need to investigate the
"p/invoke" or "interop" mechanism (two terms to describe the same thing).
This mostly involves declaring inside your C# the functions exported by a
DLL, providing various parameters to the DllImport attribute that describe
how the unmanaged code is to be called.

Pete
 
Thanks for the quick reply!

Could you please refer me to sources that explain in more detail how
to create a managed C++ dll because I seem to be missing something?

I really appreciate your help!

An
 
Could you please refer me to sources that explain in more detail how
to create a managed C++ dll because I seem to be missing something?

Sorry, I'm not aware of any. I presume they exist, but I haven't needed
to find them because it's pretty simple to do in Visual Studio. If you
really want to find the documentation, I'm sure it's in the user guide for
Visual Studio somewhere.

I have done this sort of thing simply by selecting one of the appropriate
project types under the Other Languages/C++/CLR category. In your case,
probably "Class Library" or "CLR Empty Project" (with which you can make
whatever you want) would be appropriate.

With any C++ project, you can of course go to the project properties and
change the "Configuration Type" in the "Configuration Properties/General"
page. This allows you to choose between a DLL, an EXE, or a static
library, among other things. Likewise, you could add CLR support to a
regular C++ file via the file's compilation properties. But IMHO it's
probably better to use the basic project and source file templates
provided when you create a new solution items, rather than trying to
specify everything explicitly.

Pete
 
Back
Top