实验环境:win XP , VS2008
实验中用C++语言使用STL类编写了一个字符串排序的接口,将其导出为DLL,目的是演示C++如何编写能让C调用的函数。
首先,新建一个C++空项目名称为DLL_CPP_API,将项目的输出文件类型设置为dll,添加下面两个文件
/* DLL_API.h */
#define DLL_EXPORT// 导出时需定义此宏
#ifdef DLL_EXPORT
#define DLL_API _declspec(dllexport)
extern "C" {// 导出接口时用C的连接规范
#else
#define DLL_API _declspec(dllimport)
#endif
/* 字符串排序接口 */
void DLL_API sort_string(char **strs, size_t len);
#ifdef DLL_EXPORT
}
#endif
/* DLL_body.cpp */
#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
#include "dll_API.h"
using std::string;
using std::vector;
/* C++模块内部使用的谓词 */
bool _predicate(const char *str1, const char *str2)
{
return string(str1) < string(str2);
}
/* 排序接口用C++实现 */
void sort_string(char **strs, size_t len)
{
vector<char*> vec_str;
for (size_t i = 0; i < len; ++i)
{
vec_str.push_back(strs[i]);
}
std::sort(vec_str.begin(), vec_str.end(), _predicate);
for (size_t i = 0; i < len; ++i)
{
strs[i] = vec_str[i];
}
}
/* 测试代码 */
int main()
{
char str1[] = "avdadfha";
char str2[] = "aasgdegh";
char str3[] = "aadgaahh";
char *strs[] = { str1, str2 , str3 };
sort_string(strs, 3);
std::cout << strs[0] << std::endl
<< strs[1] << std::endl
<< strs[2] << std::endl;
}
然后,新建一个C项目,名字无所谓,调用上面生成的dll(上面生成的dll和对应的lib文件要一同拷贝到当前目录),添加如下两个文件
/* DLL_API.h */
//#define DLL_EXPORT // 导出时需定义此宏
#ifdef DLL_EXPORT
#define DLL_API _declspec(dllexport)
extern "C" { // 导出接口时用C的连接规范
#else
#define DLL_API _declspec(dllimport)
#endif
/* 字符串排序接口 */
void DLL_API sort_string(char **strs, size_t len);
#ifdef DLL_EXPORT
}
#endif
/* dll_client.c */
#include <stdio.h>
#include "dll_API.h"
#pragma comment(lib, "DLL_CPP_API")
/* C语言客户端调用C++编写的API */
int main()
{
char str1[] = "avdadfha";
char str2[] = "aasgdegh";
char str3[] = "aadgaahh";
char *strs[] = { str1, str2 , str3 };
sort_string(strs, 3);
printf("%s\n%s\n%s\n", strs[0], strs[1], strs[2]);
}
运行后就可以看到字符串排序效果了