考慮我有一個動態的外部庫libExternal.dylib
以下功能的外部庫函數:傳遞爲const char *從該需要一個char *
void print(char* str)
{
// Changes the first char to 'a' and prints the string
*str = 'a';
printf("%s\n", str);
}
接下來,我有一個加載這個外部庫和調用可執行(檢查省略誤差)函數:
int main(int argc, const char * argv[])
{
void* hLib = dlopen("libExternal.dylib", RTLD_LAZY | RTLD_LOCAL);
typedef void(*printFunc)(const char*);
printFunc func = (printFunc)dlsym(hLib, "print");
std::string test = "hello";
func(test.c_str());
dlclose(hLib);
return 0;
}
正如你可以看到,在庫中定義的函數以一個char*
作爲參數。當使用dlsym
時,我使它得到了一個函數,它需要一個const char*
。它的工作原理!
我的問題是,這怎麼可能?動態加載器忽略const類型?我真的無法在任何地方找到答案,所以請幫助我! :)
編輯: 我知道這個代碼是錯誤的,我只是想了解這是如何可能的。
請注意「問題預覽」窗口,並使用正確的代碼格式(此次修復它)。 – Angew