Using Microsoft Visual Studio Professional 2019:
Created a simple addition function in C++ to generate a DLL file.
In a new C# project, referenced the above DLL file.
Win32: For both the C++ DLL and the C# program, when the active platform is set to Win32, using ‘Add reference’ in the reference manager works. The project builds and runs without any issues.
x64: For both the C++ DLL and the C# program, when the active platform is set to x64, attempting to use ‘Add reference’ in the reference manager results in a pop-up error
and the reference is not added to the project.
For my work, I need to use x64. What settings should I adjust to make this possible?
CPP file:
#include "pch.h"
#include "Divide.h"
Divide::Divide(int x) {
this->x = x;
}
int Divide::adding(int y) {
return this->x + y;
}
int Divide::get() {
return this->x;
}
extern "C" __declspec(dllexport) void* Create(int x) {
return (void*) new Divide(x);
}
extern "C" __declspec(dllexport) int DivideAdding(Divide * a, int y) {
return a->adding(y);
}
extern "C" __declspec(dllexport) int DivideGet(Divide * a) {
return a->get();
}
header file:
class Divide {
int x;
public:
Divide(int x);
int adding(int y);
int get();
};
In C#:
[DllImport("DivideDLL.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr Create(int x);
[DllImport("DivideDLL.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int DivideAdding(IntPtr a, int y);
[DllImport("DivideDLL.dll", CallingConvention = CallingConvention.Cdecl)]
public static extern int DivideGet(IntPtr a);
static void Main(string[] args)
{
try
{
IntPtr a = Create(5);
int temp = DivideGet(a);
Console.WriteLine("Initial:" + temp);
DivideAdding(a, 10);
For my work, I need to use x64. What settings should I adjust to make this possible?
If you need more information, please let me know.
6
In C# project, Add reference
is for managed DLLs.
Adding a C++ unmanaged DLL will cause a warning or error.
Visual Studio 2022:
You need to copy the C++ DLL to the output folder. Project -> Add Existing Item . Set the Copy to Output Directory property of the added item to “Copy if newer”,
And make sure the C# project architecture is consistent with the C++ DLL: properties -> Build -> Target Platform