我有一个 C++ 共享库 ( libtest-lib.so ),它通过嵌入式 Linux 平台上的 2 个 Qt 应用程序 - 应用程序 A 和应用程序 B 链接。我希望 App A 和 App B 都能够从 libtest-lib.so 引用单个共享指针。
Libtest-lib.so 很小 -
测试-lib_global.h:
#ifndef TESTLIB_GLOBAL_H
#define TESTLIB_GLOBAL_H
#include <QtCore/qglobal.h>
#if defined(TESTLIB_LIBRARY)
# define TESTLIBSHARED_EXPORT Q_DECL_EXPORT
#else
# define TESTLIBSHARED_EXPORT Q_DECL_IMPORT
#endif
#endif // TESTLIB_GLOBAL_H
测试库.h:
#ifndef TESTLIB_H
#define TESTLIB_H
#include "test-lib_global.h"
class TESTLIBSHARED_EXPORT TestLib
{
public:
TestLib();
// Notice that it is a reference
TESTLIBSHARED_EXPORT static int& GetSingleInt();
// Create a global audio buffer
TESTLIBSHARED_EXPORT static signed short* getGlobalAudioBuffer();
};
#endif // TESTLIB_H
测试库.cpp:
#include "testlib.h"
int& TestLib::GetSingleInt()
{
// keep the actual value as static to this function
int min = 5;
int max = 500;
static int s_value(min + (rand() % (int)(max - min + 1)));
// but return a reference so that everybody can use it
return s_value;
}
// Create a global audio buffer
signed short* TestLib::getGlobalAudioBuffer() {
// Create a static audio buffer
static signed short* globalAudioBuffer = (signed short*)malloc( 1000 * sizeof(signed short) );
return globalAudioBuffer;
}
TestLib::TestLib()
{
}
App A 和 App B 主要执行以下操作:
int me = TestLib::GetSingleInt();
qDebug() << "SHARED INT IS: " << me;
signed short* audioBuffer = TestLib::getGlobalAudioBuffer();
qDebug() << "SHARED AUDIO BUFFER POINTER IS: " << &audioBuffer;
当我部署 libtest-lib.so 然后构建和部署 App A 和 App B 时,我得到以下输出:
应用程序 A:
SHARED INT IS: 108
SHARED AUDIO BUFFER POINTER IS: 0xbe844ac8
应用 B:
SHARED INT IS: 108
SHARED AUDIO BUFFER POINTER IS: 0xbeff0e64
int是一样的,只是指针地址不同。我究竟做错了什么?如何从库函数返回相同的共享指针?
谢谢 -