提供我正確認識你,你應該能夠使用NSProcessInfo
的-arguments
方法來獲取可執行文件的路徑。
要將Objective-C代碼與C++代碼混合,只需將源文件的文件擴展名從.cpp更改爲.mm即可。然後將Foundation.framework添加到目標的鏈接庫二進制庫生成階段。
[編輯]更新顯示argv[0]
和[[[NSProcessInfo processInfo] arguments] objectAtIndex:0]
之間的差異。
然後使用代碼,你可以做類似下面的代碼:
#include <iostream>
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[]) {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// print out raw args
NSMutableArray *arguments = [NSMutableArray array];
for (NSUInteger i = 0; i < argc; i++) {
NSString *argument = [NSString stringWithUTF8String:argv[i]];
if (argument) [arguments addObject:argument];
}
NSLog(@"arguments == %@", arguments);
const char *executablePath =
[[[[NSProcessInfo processInfo] arguments] objectAtIndex:0]
fileSystemRepresentation];
printf("executablePath == %s\n", executablePath);
const char *executableDir =
[[[[[NSProcessInfo processInfo] arguments] objectAtIndex:0]
stringByDeletingLastPathComponent] fileSystemRepresentation];
printf("executableDir == %s\n", executableDir);
[pool release];
return 0;
}
如果我再cd
到可執行文件的父目錄,然後使用相對路徑執行可執行文件:
MacPro:~ mdouma46$ cd /Users/mdouma46/Library/Developer/Xcode/DerivedData/executablePath-ewememtbkdajumdlpnciyymduoah/Build/Products/Debug
MacPro:Debug mdouma46$ ./executablePath blah blah2
我得到以下輸出:
2011-08-10 12:59:52.161 executablePath[43554:707] arguments == (
"./executablePath",
blah,
blah2
)
executablePath == /Users/mdouma46/Library/Developer/Xcode/DerivedData/executablePath-ewememtbkdajumdlpnciyymduoah/Build/Products/Debug/executablePath
executableDir == /Users/mdouma46/Library/Developer/Xcode/DerivedData/executablePath-ewememtbkdajumdlpnciyymduoah/Build/Products/Debug
因此,雖然argv[0]
可能不一定是完整路徑,但從[[[NSProcessInfo processInfo] arguments] objectAtIndex:0]
返回的結果將是。
所以,有[[[NSProcessInfo processInfo] arguments] objectAtIndex:0]
,或者稍微簡單的方法就是使用NSBundle
本身,即使它是一個命令行工具(見What is the "main bundle" of a command-line foundation tool?):
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
const char *executablePath =
[[[NSBundle mainBundle] executablePath] fileSystemRepresentation];
[pool release];
這是一個unix可執行文件或.app包嗎? – sbooth
@sbooth unix可執行文件 – ashkash