Mac OS X上使用XCode编译调用OS X的动态库

首先创建XCode工程的时候选择Framwork & Library,然后创建动态库dynamic,

创建动态库则在Type中选择Dynamic,创建静态库则选择static

接下来的编码就像windwos或者linux中一样,最后生成的是dylib后缀的动态库,生成方式是XCode菜单栏->produce->archive编译通过后会生成dylib后缀的动态库,

编写应用程序调用动态库的时候对工程进行设置,(最后生成xxx.dylib,假定我把动态库放到了/usr/lib中,头文件xxx.h,放到/usr/local/xxx/include中)

项目设置 - Build Settings - Search Paths - Header Search Paths 加上 /usr/local/xxx/include
项目设置 - Build Settings - Linking - Other Linker Flags 加上 /usr/lib/xxx.dylib

多个文件(静态库,动态库)或目录用空格隔开,

调用静态库就简单多了

这是直接用配置的方式使用动态库,也可以直接使用代码进行动态库的打开和函数调用

编写动态库时使用代码

xxx.h

#ifndef OuBase_h
#define OuBase_h

void OuPrintA(char *szBuffer);
void OuPrintW(wchar_t *wzBuffer);


#endif

xxx.c

#include <stdio.h>
#include "xxx.h"


void OuPrintA(char *szBuffer)
{
    printf("%s \n", szBuffer);
}


void OuPrintW(wchar_t *wzBuffer)
{
    printf("sizeof wchar_t %lu %ls \n", sizeof(wchar_t), wzBuffer);
}

//可以顺便看一下wchar_t的大小,windows里面是2,linux和mac里面是4

程序调用动态库

#include <stdio.h>
#include <dlfcn.h>//dlopen和dlsym需要


typedef void (*OuPrintA)(char *szBuffer);
typedef void (*OuPrintW)(wchar_t *wzBuffer);

int main(int argc, const char * argv[]) {
    // insert code here...
    void *handle = dlopen("libOuBase.dylib", RTLD_NOW);

    if(NULL == handle)
    {
        printf("failed to dlopen libOuBase.dylib \n");
        return 1;
    }

    OuPrintA pa = dlsym(handle, "OuPrintA");
    OuPrintW pb = dlsym(handle, "OuPrintW");

    pa("my name is xxx \n");
    pb(L"my name is xxx\n");

    return 0;
}

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值