I\'ve a little question to ask you.
I have one C++ source and one header files. The C++ file uses windows.h library, makes operations using serial port(basic operati
After several comments, here a try:
C++ Code (DLL), eg. math.cpp, compiled to HighSpeedMath.dll:
extern "C"
{
__declspec(dllexport) int __stdcall math_add(int a, int b)
{
return a + b;
}
}
C# Code, eg. Program.cs:
namespace HighSpeedMathTest
{
using System.Runtime.InteropServices;
class Program
{
[DllImport("HighSpeedMath.dll", EntryPoint="math_add", CallingConvention=CallingConvention.StdCall)]
static extern int Add(int a, int b);
static void Main(string[] args)
{
int result = Add(27, 28);
}
}
}
Of course, if the entry point matches already you don't have to specify it. The same with the calling convention.
As mentioned in the comments, the DLL has to provide a C-interface. That means, extern "C", no exceptions, no references etc.
Edit:
If you have a header and a source file for your DLL, it could look like this:
math.hpp
#ifndef MATH_HPP
#define MATH_HPP
extern "C"
{
__declspec(dllexport) int __stdcall math_add(int a, int b);
}
#endif
math.cpp
#include "math.hpp"
int __stdcall math_add(int a, int b)
{
return a + b;
}
In addition to Lichian's offer to compile to a regular DLL and use p/invoke which is probably the simplest way You can also create your C++ as a COM component (probably something you don't want to do) and the 3rd option you have is to add a thin layer of C++/CLI e.g.
using namespace System;
namespace youcomany{ namespace CPPWrapper
{
Wrapper::Function(String^ parameter)
{
//call the rest of you C++ from here
}
}}
You may use C# DllImport and Dllexport for DLL Interop walkthrough as a starting point. And here is the Platform Invoke Tutorial
Hope this helps.
You need to compile your C++ code into a dynamic link library and do the following in C#:
class MyClass
{
[DllImport("MyDLL.dll")]
public static extern void MyFunctionFromDll();
static void Main()
{
MyFunctionFromDll();
}
}