自己实现的第一个linux中dll的调用
1. 编译dll:
g++ -shared -lc -o strcase.dll lowcase.cpp uppercase.cpp
如果要加入调试信息:(加上 -g选项)
g++ -shared -lc -o strcase.dll lowcase.cpp uppercase.cpp -g
编译c++ dll注意函数之前需要加上 extern "C",否则在dlsym函数调用的时候可能会找不到函数
.
2. 编译exe:
g++ -ldl -o strcase.exe main.cpp
如果要加入调试信息:(加上 -g选项)
g++ -ldl -o strcase.exe main.cpp -g
3. gdb调试
gdb strcase.exe
调试时需要在编译的时候加上(-g)选项
gdb命令:
b 设置断点,例如:
b main #表示跳到main函数
b main.cpp: 56 #56表示行号
l 打印当前的执行代码附近的10行
p 打印变量szMsg的值
p szMsg
n 执行下一行(单步执行, 类似VC中的F10)
s 进入函数(类似VC中的F10)
r 执行(类似VC中的F5)
//main.cpp
- <span style="font-size: medium;"><span style="color: #3366ff;">#include <iostream>
- #include <stdlib.h>
- #include <dlfcn.h>
- using namespace std;
- #define TRUE 1
- #define FALSE 0
- typedef int BOOL;
- typedef void (*PFUN_STRING)(char* pszStr);
- BOOL UseDll(char* szMsg);
- int main()
- {
- char szMsg[] = "Hello, andylin!";
- //调用dll
- UseDll(szMsg);
- return 0;
- }
- BOOL UseDll(char* szMsg)
- {
- void* hDll = NULL;
- char* szDllErr = NULL;
- PFUN_STRING pfunUpper = NULL;
- PFUN_STRING pfunLower = NULL;
- if (NULL == szMsg)
- {
- return FALSE;
- }
- cout << "The Origin String:" << szMsg << endl;
- //open dll
- hDll = dlopen("./strcase.dll", RTLD_LAZY);
- szDllErr = dlerror();
- if (szDllErr)
- {
- cout << "open uppercase.dll error! err info:" << szDllErr << endl;
- return FALSE;
- }
- //find the function
- pfunUpper = (PFUN_STRING)dlsym(hDll, "StrUpper");
- szDllErr = dlerror();
- if (szDllErr)
- {
- cout << "find function StrUpper Error! err info:" << szDllErr << endl;
- return FALSE;
- }
- (*pfunUpper)(szMsg);
- cout << "after StrUpper string:" << szMsg << endl;
- //call StrLower
- pfunLower = (PFUN_STRING)dlsym(hDll, "StrLower");
- szDllErr = dlerror();
- if (szDllErr)
- {
- cout << "find function StrLower Error! err info:" << szDllErr << endl;
- return FALSE;
- }
- (*pfunUpper)(szMsg);
- cout << "after StrLower string:" << szMsg << endl;
- //close handle
- int nRet = dlclose(hDll);
- szDllErr = dlerror();
- cout << "close dll info:" << szDllErr << endl;
- }
- </span></span>
//lowcase.cpp
- <span style="font-size: medium;"><span style="color: #3366ff;">#include <stdio.h>
- #include <stdlib.h>
- #include <iostream>
- using namespace std;
- extern "C" void StrLower(char* pszStr)
- {
- if (NULL == pszStr)
- {
- return;
- }
- int nLen = 0;
- int i = 0;
- nLen = strlen(pszStr);
- for (i = 0; i < nLen; i++)
- {
- if ( (pszStr[i] >= 'A') && (pszStr[i] <= 'Z') )
- {
- pszStr[i] += 26;
- }
- }
- }
- </span></span>
//uppercase.cpp
- <span style="font-size: medium;"><span style="color: #3366ff;">#include <stdio.h>
- #include <stdlib.h>
- #include <iostream>
- using namespace std;
- extern "C" void StrUpper(char* pszStr)
- {
- if (NULL == pszStr)
- {
- return;
- }
- int nLen = 0;
- int i = 0;
- nLen = strlen(pszStr);
- for (i = 0; i < nLen; i++)
- {
- if ( (pszStr[i] >= 'a') && (pszStr[i] <= 'z') )
- {
- pszStr[i] -= 26;
- }
- }
- }</span>
- </span>