C调用C++接口

C文件

#include <ctype.h>
#include <sys/time.h>
#include <sys/stat.h>
#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#include <unistd.h>
#include <signal.h>
#include <dirent.h>
#include <unistd.h>
#include <sys/stat.h>
#include <fcntl.h>
#include<stdio.h>
#include<sys/socket.h>
#include<netinet/in.h>
#include<arpa/inet.h>
#include<assert.h>
#include<unistd.h>
#include<stdlib.h>
#include<errno.h>
#include<string.h>
#include<sys/types.h>
#include<fcntl.h>
#include<time.h>
#include<aio.h>

extern "C" void funCPP();

extern "C" void funC() {
    printf("funC, call funCPP\n");
    funCPP();
}

C++文件

#include <iostream>
#include <mutex>
#include <unistd.h>
#include <vector>
#include <algorithm>
#include <fstream>
#include <thread>
#include <string>
#include <functional>
#include <future>
#include <map>
#include <unordered_map>
#include <iostream>     // std::cout
#include <future>       // std::packaged_task, std::future
#include <chrono>       // std::chrono::seconds
#include <thread>       // std::thread, std::this_thread::sleep_for
#include <cstring>

extern "C" void funC();
using namespace std;


class Base {
public:
    Base() {
        cout << "base ctor" << endl;
    }

    virtual ~Base() {
        cout << "base dtor" << endl;
    }

    virtual void fun() {
        cout << "base fun" << endl;
    }
};

class Drive: public Base {
public:
    Drive(): i(6) {
        cout << "Drive ctor" << endl;
    }

    virtual ~Drive() {
        cout << "Drive dtor" << endl;
    }

    void fun() override final {
        cout << "drive fun" << endl;
    }

    const int i = 5;

};

class Drive2 : public Drive {
public:
    Drive2() = default;

    //void fun() {
    //    cout << "drive2 fun" << endl;
};

extern "C" void funCPP() {
    Base* d = new Drive2;

    d->fun();
    cout << "funCPP" << endl;
}

void fun1() {

    cout << "fun1" << endl;
}



int main () {
    fun1();
    funC();

  return 0;
}

编译运行:

g++ -std=c++11 test.cpp test.c
./a.out
fun1
funC, call funCPP
base ctor
Drive ctor
drive fun
funCPP

主要利用了C++的语言链接声明 extern “C” void funCPP,使得funCPP以C方式进行编译链接,让C语言的代码能够找到funCPP接口。

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值