Creating a C++ DLL and then using it in C#
- by Major
Ok I'm trying to make a C++ DLL that I can then call and reference in a c# App. I've already made a simple dll using the numberous guides out there, however when I try to reference it in the C# app I get the error
Unable to load DLL 'SDES.dll': The specified module could not be found.
The code for the program is as follows (bear with me I'm going to include all the files)
//These are the DLL Files.
ifndef TestDLL_H
define TestDLL_H
extern "C"
{
// Returns a + b
__declspec(dllexport) double Add(double a, double b);
// Returns a - b
__declspec(dllexport) double Subtract(double a, double b);
// Returns a * b
__declspec(dllexport) double Multiply(double a, double b);
// Returns a / b
// Throws DivideByZeroException if b is 0
__declspec(dllexport) double Divide(double a, double b);
}
endif
//.cpp
include "test.h"
include
using namespace std;
extern double __cdecl Add(double a, double b)
{
return a + b;
}
extern double __cdecl Subtract(double a, double b)
{
return a - b;
}
extern double __cdecl Multiply(double a, double b)
{
return a * b;
}
extern double __cdecl Divide(double a, double b)
{
if (b == 0)
{
throw new invalid_argument("b cannot be zero!");
}
return a / b;
}
//C# Program
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace ConsoleApplication1
{
class Program
{
[DllImport("SDES.dll")]
public static extern void SimulateGameDLL(int a, int b);
static void Main(string[] args)
{
SimulateGameDLL(1, 2); //Error here...
}
}
}
Anyone have any idea's what I may be missing in my program? Let me know if I missed some code or if you have any questions.