考虑我有一个动态的外部库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