I have a C++ shared library ( libtest-lib.so ) that is linked against by 2 Qt Apps – App A and App B on an embedded Linux platform. I want to be able to reference a single shared pointer from libtest-lib.so by both App A and App B.
Libtest-lib.so is tiny –
test-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
testlib.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
testlib.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()
{
}
Both App A and App B do the following in their main:
int me = TestLib::GetSingleInt();
qDebug() << "SHARED INT IS: " << me;
signed short* audioBuffer = TestLib::getGlobalAudioBuffer();
qDebug() << "SHARED AUDIO BUFFER POINTER IS: " << &audioBuffer;
When I deploy libtest-lib.so and then build and deploy App A and App B, I get the following output:
App A:
SHARED INT IS: 108
SHARED AUDIO BUFFER POINTER IS: 0xbe844ac8
App B:
SHARED INT IS: 108
SHARED AUDIO BUFFER POINTER IS: 0xbeff0e64
The int is the same, but the pointer address is different. What am I doing wrong? How can I return an identical shared pointer from the library function?
Thanks –
That’s not possible per se. Each process has its separate address space. A shared library shares instructions and data, not memory at runtime. You would have to use shared memory and synchronize between processes accordingly. Qt offers QSharedMemory, which provides a platform-independent API to a raw chunk of shared memory with some basic semaphore-based lock/unlock mechanism for synchronization.
Alternatively, use another IPC mechanism to stream the audio data, e.g. pipes or sockets. That might make synchronization a whole lot easier, depending on the complexity of interaction between the processes.