首先得有一个c++程序,我们这里叫test.
其中代码
test.h
{
class MyMath
{
public:
__declspec(dllexport) float Mysub(float a, float b);
};
}
test.cpp
{
#include "stdafx.h"
#include "test.h"
extern "C"__declspec(dllexport) float MyAdd(float a, float b)
{
return (a + b);
}
float MyMath::Mysub(float a, float b)
{
return a - b;
}
}
test.def
{
LIBRARY
EXPORTS
Mysub @1
MyAdd @2
}(注:这个文件很重要,如果没有的话,在c#中调用类中的函数sub的时候,就会找不到sub入口点,不过还有一种解决方法,就是EntryPoint="?Mysub@MyMath@@QAEMMM@Z".其中引号中的内容可以在test.exp文件中找到。)
但是如果有这个文件的话就可以省去找EntryPoint那里引号中的内容。
然后我们有一个c#程序,我们这里叫dlltest.
其中代码
新建了一个类MyMath.cs(名字不重要),它主要是为了接受c++中的方法,这样在c#通过这个类找到那些方法就比较方便了。
MyMath.cs
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
namespace dlltest
{
class MyMath
{
[DllImport("test.dll", EntryPoint = "Mysub")]
public static extern float Mysub(float a,float b);
[DllImport("test.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "MyAdd")]
public static extern float MyAdd(float a,float b);
}
}
}
主函数Program.cs
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(MyMath.MyAdd(1, 2));
Console.WriteLine(MyMath.Mysub(5,1));
Console.ReadKey();
}
}
其中代码
test.h
{
class MyMath
{
public:
__declspec(dllexport) float Mysub(float a, float b);
};
}
test.cpp
{
#include "stdafx.h"
#include "test.h"
extern "C"__declspec(dllexport) float MyAdd(float a, float b)
{
return (a + b);
}
float MyMath::Mysub(float a, float b)
{
return a - b;
}
}
test.def
{
LIBRARY
EXPORTS
Mysub @1
MyAdd @2
}(注:这个文件很重要,如果没有的话,在c#中调用类中的函数sub的时候,就会找不到sub入口点,不过还有一种解决方法,就是EntryPoint="?Mysub@MyMath@@QAEMMM@Z".其中引号中的内容可以在test.exp文件中找到。)
但是如果有这个文件的话就可以省去找EntryPoint那里引号中的内容。
然后我们有一个c#程序,我们这里叫dlltest.
其中代码
新建了一个类MyMath.cs(名字不重要),它主要是为了接受c++中的方法,这样在c#通过这个类找到那些方法就比较方便了。
MyMath.cs
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
namespace dlltest
{
class MyMath
{
[DllImport("test.dll", EntryPoint = "Mysub")]
public static extern float Mysub(float a,float b);
[DllImport("test.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "MyAdd")]
public static extern float MyAdd(float a,float b);
}
}
}
主函数Program.cs
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(MyMath.MyAdd(1, 2));
Console.WriteLine(MyMath.Mysub(5,1));
Console.ReadKey();
}
}