zoukankan      html  css  js  c++  java
  • C与C++之间相互调用

    http://www.cnblogs.com/luxiaoxun/p/3405374.html

    1、导出C函数以用于C或C++的项目

    如果使用C语言编写的DLL,希望从中导出函数给C或C++的模块访问,则应使用 __cplusplus 预处理器宏确定正在编译的语言。如果是从C++语言模块使用,则用C链接声明这些函数。如果使用此技术并为DLL提供头文件,则这些函数可以原封不动地由C和C++模块使用。

    以下代码演示可由 C 和 C++ 客户端应用程序使用的头文件:

    复制代码
    // MyCFuncs.h
    #ifdef __cplusplus
    extern "C" {  // only need to export C interface if
                  // used by C++ source code
    #endif
    
    __declspec( dllimport ) void MyCFunc();
    __declspec( dllimport ) void AnotherCFunc();
    
    #ifdef __cplusplus
    }
    #endif
    复制代码

    MyCFunc()和AnotherCFunc()为C语言DLL的导出函数。

    如果需要将C函数链接到C++可执行文件,并且函数声明头文件没有使用上面的技术,则在C++源文件中添加下列内容以防止编译器修饰C函数名:

    extern "C" 
    {
    #include "MyCHeader.h"
    }

    该代码告诉编译器"MyCHeader.h"是C写的,不要修饰头文件中的C函数名,否则连接的时候会找不到。

    2、导出 C++ 函数以用于C语言项目

    如果在用C++编写的DLL中有希望从C语言模块访问的函数,应使用C链接而不是C++链接来声明这些函数。除非另外指定,C++编译器使用C++类型安全命名约定(也称作名称修饰)和C++调用约定(使用此调用约定从C调用会很困难)。

    若要指定 C 链接,请在DLL中为函数声明指定 extern "C"。例如:

    extern "C" __declspec( dllexport ) int MyFunc(long parm1);

    在C语言的函数中是无法直接调用C++代码的,如果要调用,可以做一个wrapper,例如call_Lib_CPPFunction,它的声明和实现如下:

    复制代码
    // wrapper function
    extern "C" void call_Lib_CPPFunction(Lib* p, DataAttribute* dataAttribute) 
    {
        p->daFun(dataAttribute);
    } 
    
    // daFun才是我们C++代码的实现
    void Lib::daFun(DataAttribute* dataAttribute)
    {
        map<string, MMSINFO>::iterator it;
        // ...
    }
    复制代码
  • 相关阅读:
    使用JDBC连接MySql时出现:The server time zone value '�й���׼ʱ��' is unrecognized or represents more than one time zone. You must configure either the server or JDBC driver (via the serverTimezone configuration
    Mysql Lost connection to MySQL server at ‘reading initial communication packet', system error: 0
    mysql-基本命令
    C# 监听值的变化
    DataGrid样式
    C# 获取当前日期时间
    C# 中生成随机数
    递归和迭代
    PHP 时间转几分几秒
    PHP 根据整数ID,生成唯一字符串
  • 原文地址:https://www.cnblogs.com/feng9exe/p/7133027.html
Copyright © 2011-2022 走看看