第1个回答 2014-09-11
写动态库:
/*
* libsthcpp.h
* Declarations for function cppadd //声明函数cppadd
*/
#include "stdio.h"
#include "stdlib.h"
#include "stdarg.h" //stdandard argument(标准参数),用的都是c的头文件,方便以后c调用?
#ifdef __cplusplus //参考我之前的文章
extern "C"
{
#endif
int cppadd(int x, int y); //不用类来写c++!没有参考性,凑合看了
#ifdef __cplusplus
}
#endif
/*
* libsthcpp.cpp
* Implementation of function cppadd declared in libsthcpp.h//实现函数
* in c++ language
*/
#include "libsthcpp.h"
//和之前说的不同,前面说的使用externa "C"关键字,对于c++被c调用的,cpp文件中,也要写上去。
int cppadd(int x, int y)
{
return x + y;
}
C#调用DLL
使用C#时不免用调用别的DLL,如WIN32的API和自己以前做的DLL,包括不同语言之间的的dll
C#调用DLL很像VB,下面讨论的C#调用DLL的方式。
看看下面的例子,演示了怎么定义DLL函数接口
public class Utility
{
[DllImport("kernel32",
EntryPoint="CreateDirectory",
CallingConvention=CallingConvention.StdCall)]
public static extern bool Create (string name);
[DllImport("User32",
EntryPoint="MessageBox",
CallingConvention=CallingConvention.StdCall)]
public static extern int MsgBox (string msg);
}
class MyClass
{
public static int Main()
{
string myString;
Console.Write("Enter your message: ");
myString = Console.ReadLine();
return Utility.MsgBox(myString);
}
}
值得注意的是,缺省的调用规则(CallingConvention)是Stdcall,同Winapi,在
C++里是__stdcall的形式,函数入口(EntryPoint)缺省是同名,如CreateDirectory
的定义也可以为
[DllImport("kernel32")]
static extern bool CreateDirectory(string name, SecurityAttributes sa);
WIN32 API原型为
BOOL CreateDirectory(
LPCTSTR lpPathName, // directory name
LPSECURITY_ATTRIBUTES lpSecurityAttributes // SD
);