[StructLayout(LayoutKind.Sequential)]
public class MyOGRE
{
//该方式是直接调用C++ DLL内的类的成员函数。
[DllImport("CPlusPlusCSharpMix.dll", EntryPoint = "?MyOGREHello@MyOGRE@@QAEXXZ")]
public static extern void MyOGREHello();
}
类中成员函数找不到,需要设置入口点。利用depends.exe可以查看到程序入口点。
在C#中调用静态程序直接用. 而不是::, 所以要调用MyOGREHello() 如下:
Graphics.MyOGRE.MyOGREHello();
#ifndef __GRAPHICS_H__
#define __GRAPHICS_H__
#pragma once
#define DLL_EXPORTS
#ifdef DLL_EXPORTS
#define DLL_API extern "C" __declspec(dllexport)
#define DLL_CLASS __declspec(dllexport)
#else
#define DLL_API extern "C" __declspec(dllimport)
#define DLL_CLASS __declspec(dllimport)
#endif
#include <iostream>
DLL_API bool Init();
DLL_API bool Run();
DLL_API bool Clean();
DLL_API bool Init1(std::string str);
DLL_API bool Init2(int a);
DLL_API bool Init3(int* a);
DLL_API bool Init4(int a[]);
DLL_API bool Init5(int** a);
DLL_API bool Init25(int& a);
DLL_API bool Init6(int*& a);
class DLL_CLASS MyOGRE
{
public:
MyOGRE()
{
mname = "Thank you all the same Mr.王";
}
void MyOGREHello()
{
std::cout<<"Hello MyOGRE_Hello()"<<std::endl;
}
std::string GetString()
{
return mname;
}
private:
std::string mname;
};
DLL_API MyOGRE* GetOGRE();
DLL_API MyOGRE& GetOGREInst();
#endif//__GRAPHICS_H__
能导出类与导出类成员,基本的应用就够了。
为了传递数据,托管代码与非托管代码,比如string类型的长度不知道,那么利用下面的
来限定非托管代码的长度。[MarshalAs(UnmanagedType.LPArray, SizeConst=10)]