gpt4 book ai didi

c - 如何在 Obj-C 应用程序中访问和使用 dylib?

转载 作者:太空宇宙 更新时间:2023-11-03 23:35:25 24 4
gpt4 key购买 nike

我制作了一个包含以下代码的动态库:

    Test.h:

#import <Cocoa/Cocoa.h>
@interface Test : NSObject {
int number;
}
-(void)beep;
-(void)giveInt:(int)num;
-(int)takeInt;

@end


Test.m:

#import "Test.h"

@implementation Test

-(void)beep {
NSBeep();
}
-(void)giveInt:(int)num {
number = num;
}
-(int)takeInt {
return number;
}

@end

我已经编译了 dylib 并将其放在另一个项目中,但我似乎无法弄清楚如何从 dylib 中创建一个 Test 对象并调用其中的一些方法。
有人知道怎么做吗?
谢谢,
马特

最佳答案

仅供引用:动态库在运行时加载。如果您不需要动态加载代码,请静态链接。

无论如何:

#import "test.h"
#include <dlfcn.h>

int main(int argc, const char *argv) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

void *handle = dlopen("test.dylib", RTLD_LAZY);
id t = [[NSClassFromString(@"Test") alloc] init];

[t beep];
[t release];

dlclose(handle);
[pool drain];
}

您需要包括一些错误检查,但这是基本的想法。如果你想使用 NSBundle(根据情况可能更“合适”,参见 http://developer.apple.com/library/mac/#documentation/CoreFoundation/Conceptual/CFBundles/AccessingaBundlesContents/AccessingaBundlesContents.html )

关于c - 如何在 Obj-C 应用程序中访问和使用 dylib?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5129022/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com