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接口。

上一篇:Intel 和 ARM 对ROP/COP/JOP的缓解措施-二、COP/JOP


下一篇:【Android】在渲染生效前提前测量View大小