C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
DLL settings:
Configuration Type:
Dynamic Library (.dll)
Use of MFC:
Use Standard Windows Libaries
Use of ATL:
Not Using ATL
Common Language Runtime Support:
No Common Language Runtime Support
Whole Program Optimization:
Use Link Time Code Generation
Also: In the Linker property page, you can set the output name of the DLL, such as the name CoreDLL.dll.
Program fragment that uses dllexport: C++
// This code should be put in a header file for your C++ DLL. It declares
// an extern C function that receives two parameters and is called SimulateGameDLL.
// I suggest putting it at the top of a header file.
extern "C" {
__declspec(dllexport) void __cdecl SimulateGameDLL (int a, int b);
}
Program fragment that implements method: C++
// The keywords and parameter types must match
// ... the above extern declaration.
extern void __cdecl SimulateGameDLL (int num_games, int rand_in) {
// This is part of the DLL, so we can call any function we want
// in the C++. The parameters can have any names we want to give
// them and they don't need to match the extern declaration.
}
Program fragment that calls DLL method: C#
/// <summary>
/// A C-Sharp interface to the DLL, written in C++.
/// </summary>
static class GameSharp
{
/// <summary>
/// The native methods in the DLL's unmanaged code.
/// </summary>
internal static class UnsafeNativeMethods
{
const string _dllLocation = "CoreDLL.dll";
[DllImport(_dllLocation)]
public static extern void SimulateGameDLL(int a, int b);
}
}
Program fragment that uses UnsafeNativeMethods: C#
static class GameSharp
{
// [code omitted, see above example]
/// <summary>
/// Simulate N games in the DLL.
/// </summary>
public static void SimulateGameCall(int num)
{
UnsafeNativeMethods.SimulateGameDLL(num, new Random().Next());
}
}
Also: The DLL export method must have the same name, although its parameter names aren't important.
MarshalAs: You must use MarshalAs for when you have a char* pointer, although there are other options.
UnsafeTip: It is often best to have both the C++ DLL and the C# code in the same solution in Visual Studio. This helps them work together.
Review: This is not a comprehensive guide to C++ interop with C# code, but it contains material that can help you get started.