如何让C++ 和 STL 为C服务

实验环境: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]);
}

运行后就可以看到字符串排序效果了



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值