Hello I'm trying to implement simple client/server CORBA app with docker. Here is Print.idl code :
module Test
{
interface Printer
{
void print();
};
};
Here is the client code:
#include <iostream>
#include "PrintC.h"
int main(int argc, char** argv) {
try {
CORBA::ORB_var orb = CORBA::ORB_init(argc, argv);
CORBA::Object_var po = orb->string_to_object("corbaname::nameservice/NameService#test/Printer");
Test::Printer_var p = Test::Printer::_narrow(po.in());
p->print();
orb->destroy();
} catch (CORBA::Exception const& e) {
std::cerr << "CORBA exception raised: " << e._name() << ": " << e._info().c_str() << '\n';
}
return 0;
}
Here is the server code:
#include <iostream>
#include <orbsvcs/CosNamingC.h>
#include "PrintS.h"
class Implement_Printer : public POA_Test::Printer {
public:
void print() {
std:: cout << "Hello World\n";
}
};
int main(int argc, char** argv) {
try {
CORBA::ORB_var orb = CORBA::ORB_init(argc, argv);
CORBA::Object_var object = orb->resolve_initial_references("RootPOA");
PortableServer::POA_var poa = PortableServer::POA::_narrow(object.in());
PortableServer::POAManager_var poa_manager = poa->the_POAManager();
poa_manager->activate();
Implement_Printer p;
Test::Printer_var printer_object = p._this();
object = orb->string_to_object("corbaloc::nameservice/NameService");
CosNaming::NamingContextExt_var naming_context =
CosNaming::NamingContextExt::_narrow(object.in());
CosNaming::Name_var name;
name = naming_context->to_name("test/Printer");
naming_context->rebind(name.in(), printer_object.in());
orb->run();
poa->destroy(1, 1);
orb->destroy();
} catch (CORBA::Exception const& e) {
std::cerr << "CORBA exception raised: " << e;
}
return 0;
}
And here is the docker-compose.yml :
version: '3.2'
services:
serveur:
image: serveur
networks:
- corba
depends_on:
- nameservice
client:
image: client
networks:
- corba
depends_on:
- nameservice
- serveur
nameservice:
image: omninames
networks:
- corba
networks:
corba:
driver: bridge
Here is the log of docker-compose up :
nameservice_1 | omniNames: (0) 2020-06-10 15:47:16.221353: Data file: '/var/lib/omniorb/omninames-13afbf6c0191.dat'.
nameservice_1 | omniNames: (0) 2020-06-10 15:47:16.221588: Starting omniNames for the first time.
nameservice_1 | omniNames: (0) 2020-06-10 15:47:16.222368: Wrote initial data file '/var/lib/omniorb/omninames-13afbf6c0191.dat'.
nameservice_1 | omniNames: (0) 2020-06-10 15:47:16.222446: Read data file '/var/lib/omniorb/omninames-13afbf6c0191.dat' successfully.
nameservice_1 | omniNames: (0) 2020-06-10 15:47:16.222496: Root context is IOR:010000002b00000049444c3a6f6d672e6f72672f436f734e616d696e672f4e616d696e67436f6e746578744578743a312e300000010000000000000070000000010102000e0000003139322e3136382e3230382e3200f90a0b0000004e616d6553657276696365000300000000000000080000000100000000545441010000001c0000000100000001000100010000000100010509010100010000000901010003545441080000008400e15e01000001
nameservice_1 | omniNames: (0) 2020-06-10 15:47:16.222546: Checkpointing Phase 1: Prepare.
nameservice_1 | omniNames: (0) 2020-06-10 15:47:16.222634: Checkpointing Phase 2: Commit.
nameservice_1 | omniNames: (0) 2020-06-10 15:47:16.222783: Checkpointing completed.
serveur_1 | CORBA exception raised: NotFound (IDL:omg.org/CosNaming/NamingContext/NotFound:1.0)
corba_docker_serveur_1 exited with code 139
corba_docker_client_1 exited with code 139
According to the doc the error is due to "The Name or one of its components, could not be found. If this exception is raised because the binding already exists or the binding is of the wrong type, the rest_of_name member of the exception has a length of 1."
This code is inspired of https://github.com/cromo/multicontainer-corba/
Thanks to Wireshark, I have obtained more info about the error.
wireshark
Thus it seems to replace :
name = naming_context->to_name("test/Printer")
by
name = naming_context->to_name("Printer")
works. (Same thing for the client code)
Related
I've got simple C++ Windows program that prints stack trace. Tried different codes I found on internet and still getting same results. When optimizations are off, things get displayed correctly. Once I turn them on(or switch from Debug build to Release build in VS), specifically I use /O2(but doesn't work with other optimization flags too), only main function gets printed on screen even though there should be more functions on stack. I thought that maybe that function gets inlined but I think that this isn't the case, I can turn any optimization setting on, like force inline anywhere possible etc. and just works fine, once I turn on /O2, /O1 etc. it shows just main. PDB files are generated so that shouldn't cause any problems.
I'd appreciate any help, or if anyone knows some other way/library to show stack trace.
Output with optimizations off, you can see func2 and func3 displayed correctly:
Line: 78 | Function name: func2 | Module name: D:\ConsoleApplication3\Debug\ConsoleApplication3.exe
Line: 83 | Function name: func3 | Module name: D:\ConsoleApplication3\Debug\ConsoleApplication3.exe
Line: 88 | Function name: main | Module name: D:\ConsoleApplication3\Debug\ConsoleApplication3.exe
Line: 78 | Function name: invoke_main | Module name: D:\ConsoleApplication3\Debug\ConsoleApplication3.exe
Line: 288 | Function name: __scrt_common_main_seh | Module name: D:\ConsoleApplication3\Debug\ConsoleApplication3.exe
Line: 331 | Function name: __scrt_common_main | Module name: D:\ConsoleApplication3\Debug\ConsoleApplication3.exe
Line: 17 | Function name: mainCRTStartup | Module name: D:\ConsoleApplication3\Debug\ConsoleApplication3.exe
Line: 0 | Function name: BaseThreadInitThunk | Module name: C:\WINDOWS\System32\KERNEL32.DLL
Line: 0 | Function name: RtlGetFullPathName_UEx | Module name: C:\WINDOWS\SYSTEM32\ntdll.dll
L
Output with /O2 flag, func2 and func3 are missing:
Line: 88 | Function name: main | Module name: D:\ConsoleApplication3\Release\ConsoleApplication3.exe
Line: 288 | Function name: __scrt_common_main_seh | Module name: D:\ConsoleApplication3\Release\ConsoleApplication3.exe
Line: 0 | Function name: BaseThreadInitThunk | Module name: C:\WINDOWS\System32\KERNEL32.DLL
Line: 0 | Function name: RtlGetFullPathName_UEx | Module name: C:\WINDOWS\SYSTEM32\ntdll.dll
Line: 0 | Function name: RtlGetFullPathName_UEx | Module name: C:\WINDOWS\SYSTEM32\ntdll.dll
This is code I am currently using, this runs only on x86:
#include <windows.h>
#include <iostream>
#include <dbghelp.h>
void stacktrace()
{
DWORD machine = IMAGE_FILE_MACHINE_I386;
HANDLE process = GetCurrentProcess();
HANDLE thread = GetCurrentThread();
CONTEXT context = {};
context.ContextFlags = CONTEXT_FULL;
RtlCaptureContext(&context);
SymInitialize(process, NULL, TRUE);
SymSetOptions(SYMOPT_LOAD_LINES);
STACKFRAME frame = {};
frame.AddrPC.Offset = context.Eip;
frame.AddrPC.Mode = AddrModeFlat;
frame.AddrFrame.Offset = context.Ebp;
frame.AddrFrame.Mode = AddrModeFlat;
frame.AddrStack.Offset = context.Esp;
frame.AddrStack.Mode = AddrModeFlat;
while (StackWalk(machine, process, thread, &frame, &context, NULL, SymFunctionTableAccess, SymGetModuleBase, NULL))
{
DWORD64 functionAddress;
std::string moduleName;
std::string functioName;
std::string file;
unsigned int _line = 0;
functionAddress = frame.AddrPC.Offset;
DWORD moduleBase = SymGetModuleBase(process, frame.AddrPC.Offset);
char moduleBuff[MAX_PATH];
if (moduleBase && GetModuleFileNameA((HINSTANCE)moduleBase, moduleBuff, MAX_PATH))
{
moduleName = moduleBuff;
}
char symbolBuffer[sizeof(IMAGEHLP_SYMBOL) + 255];
PIMAGEHLP_SYMBOL symbol = (PIMAGEHLP_SYMBOL)symbolBuffer;
symbol->SizeOfStruct = (sizeof IMAGEHLP_SYMBOL) + 255;
symbol->MaxNameLength = 254;
if (SymGetSymFromAddr(process, frame.AddrPC.Offset, NULL, symbol))
{
functioName = symbol->Name;
}
DWORD offset = 0;
IMAGEHLP_LINE line;
line.SizeOfStruct = sizeof(IMAGEHLP_LINE);
if (SymGetLineFromAddr(process, frame.AddrPC.Offset, &offset, &line))
{
file = line.FileName;
_line = line.LineNumber;
}
std::cout
<< "Line: " << _line
<< " | Function name: " << functioName
<< " | Module name: " << moduleName
<< std::endl;
}
SymCleanup(process);
}
void func2()
{
stacktrace();
}
void func3()
{
func2();
}
int main()
{
func3();
system("pause");
return 0;
}
I'm trying to write a C++ program, that sends a bunch of images and converts them into a RTSP stream. After some grinding, I've came up with the code for that. VLC seems to connect to the server, but it gets no data, then it quits... Can anyone tell me what I'm doing wrong? Thank you!
VLC just tells me this:
main debug: processing request item: rtsp://192.168.56.1/ScreenShots, node: Playlist, skip: 0
main debug: rebuilding array of current - root Playlist
main debug: rebuild done - 1 items, index 0
main debug: starting playback of new item
main debug: resyncing on rtsp://192.168.56.1/ScreenShots
main debug: rtsp://192.168.56.1/ScreenShots is at 0
main debug: creating new input thread
main debug: Creating an input for 'rtsp://192.168.56.1/ScreenShots'
main debug: requesting art for new input thread
main debug: using timeshift granularity of 50 MiB
main debug: using timeshift path: C:\Users\Benny\AppData\Local\Temp
main debug: looking for meta fetcher module matching "any": 1 candidates
main debug: `rtsp://192.168.56.1/ScreenShots' gives access `rtsp' demux `any' path `192.168.56.1/ScreenShots'
main debug: creating demux: access='rtsp' demux='any' location='192.168.56.1/ScreenShots' file='\\192.168.56.1\ScreenShots'
main debug: looking for access_demux module matching "rtsp": 15 candidates
lua debug: Trying Lua scripts in C:\Users\Benny\AppData\Roaming\vlc\lua\meta\fetcher
lua debug: Trying Lua scripts in C:\Program Files\VideoLAN\VLC\lua\meta\fetcher
main debug: no meta fetcher modules matched
main debug: looking for art finder module matching "any": 2 candidates
live555 debug: version 2016.11.28
lua debug: Trying Lua scripts in C:\Users\Benny\AppData\Roaming\vlc\lua\meta\art
lua debug: Trying Lua scripts in C:\Program Files\VideoLAN\VLC\lua\meta\art
lua debug: Trying Lua playlist script C:\Program Files\VideoLAN\VLC\lua\meta\art\00_musicbrainz.luac
lua debug: skipping script (unmatched scope) C:\Program Files\VideoLAN\VLC\lua\meta\art\00_musicbrainz.luac
lua debug: Trying Lua playlist script C:\Program Files\VideoLAN\VLC\lua\meta\art\01_googleimage.luac
lua debug: skipping script (unmatched scope) C:\Program Files\VideoLAN\VLC\lua\meta\art\01_googleimage.luac
lua debug: Trying Lua playlist script C:\Program Files\VideoLAN\VLC\lua\meta\art\02_frenchtv.luac
lua debug: skipping script (unmatched scope) C:\Program Files\VideoLAN\VLC\lua\meta\art\02_frenchtv.luac
lua debug: Trying Lua playlist script C:\Program Files\VideoLAN\VLC\lua\meta\art\03_lastfm.luac
lua debug: skipping script (unmatched scope) C:\Program Files\VideoLAN\VLC\lua\meta\art\03_lastfm.luac
main debug: no art finder modules matched
live555 debug: RTP subsession 'video/H264'
qt debug: IM: Setting an input
main debug: selecting program id=0
live555 debug: setup start: 0.000000 stop:0.000000
live555 debug: We have a timeout of 65 seconds
live555 debug: play start: 0.000000 stop:0.000000
main debug: using access_demux module "live555"
main debug: looking for packetizer module matching "any": 25 candidates
h264 debug: found NAL_SPS (sps_id=7)
h264 debug: found NAL_PPS (pps_id=7 sps_id=7)
main debug: using packetizer module "h264"
main debug: looking for video decoder module matching "any": 19 candidates
avcodec debug: using ffmpeg Lavc58.6.103
avcodec debug: CPU flags: 0x000fd3db
avcodec debug: allowing 6 thread(s) for decoding
avcodec debug: codec (h264) started
avcodec debug: using frame thread mode with 6 threads
main debug: using video decoder module "avcodec"
main debug: looking for meta reader module matching "any": 2 candidates
lua debug: Trying Lua scripts in C:\Users\Benny\AppData\Roaming\vlc\lua\meta\reader
lua debug: Trying Lua scripts in C:\Program Files\VideoLAN\VLC\lua\meta\reader
lua debug: Trying Lua playlist script C:\Program Files\VideoLAN\VLC\lua\meta\reader\filename.luac
main debug: no meta reader modules matched
main debug: `rtsp://192.168.56.1/ScreenShots' successfully opened
live555 error: no data received in 10s, aborting
main debug: EOF reached
main debug: killing decoder fourcc `h264'
main debug: removing module "avcodec"
main debug: removing module "h264"
main debug: removing module "live555"
main debug: Program doesn't contain anymore ES
main debug: dead input
main debug: changing item without a request (current 0/1)
main debug: nothing to play
qt debug: IM: Deleting the input
Here is how I do this in code:
Starting the server:
void startServer(void * aArg) {
rtspServer = new OTPRTSPServer(554);
if (!rtspServer->init(DEFAULT_MONITOR.maxResolution.width, DEFAULT_MONITOR.maxResolution.height, 20)) {
cerr << "Could not start the RTSP Server" << endl;
exit(1);
}
rtspServer->addSession("ScreenShots");
rtspServer->play();
readyToSetFrame = true;
rtspServer->doEvent();
}
Here are the RTSPServer functions that I've wrote:
bool init(int srcWidth, int srcHeight, int fps) {
m_srcWidth = srcWidth;
m_srcHeight = srcHeight;
m_fps = fps;
OutPacketBuffer::maxSize = 100000;
int cNameLen = 100;
m_cName.resize(cNameLen + 1, 0);
gethostname((char*)&(m_cName[0]), cNameLen);
m_rtspServer = RTSPServer::createNew(*m_env, m_rtspPort, nullptr);
if (m_rtspServer == nullptr) {
std::cerr << "Failed to create RTSP server: " << m_env->getResultMsg() << std::endl;
return false;
}
m_screenSource = ScreenSource::createNew(*m_env, m_srcWidth * m_srcHeight, 10);
if (!m_screenSource->openEncoder(m_srcWidth, m_srcHeight, m_fps)) {
std::cerr << "Failed to open X264 encoder: " << std::endl;
return false;
}
return true;
}
void addSession(const std::string& streamName) {
sockaddr_storage destinationAddress;
((struct sockaddr_in&)destinationAddress).sin_addr.s_addr = chooseRandomIPv4SSMAddress(*m_env);
const Port rtpPort(m_rtpPortNum);
const Port rtcpPort(m_rtcpPortNum);
auto rtpGroupSock = new Groupsock(*m_env, destinationAddress, rtpPort, m_ttl);
m_rtpGroupSock->multicastSendOnly();
auto rtcpGroupSock = new Groupsock(*m_env, destinationAddress, rtcpPort, m_ttl);
m_rtcpGroupSock->multicastSendOnly();
m_videoSink = H264VideoRTPSink::createNew(*m_env, rtpGroupSock, m_rtpPayloadFormat);
m_rtcp = RTCPInstance::createNew(*m_env, rtcpGroupSock, m_estimatedSessionBandwidth, &(m_cName[0]), m_videoSink, nullptr, True);
auto sms = ServerMediaSession::createNew(*m_env, streamName.c_str(), "Screen image", "Image from the screen", True);
sms->addSubsession(PassiveServerMediaSubsession::createNew(*m_videoSink, m_rtcp));
m_rtspServer->addServerMediaSession(sms);
std::cout << "Play this stream using the Local URL: " << m_rtspServer->rtspURL(sms) << std::endl;
}
inline void play() {
m_videoES = m_screenSource;
m_videoSource = H264VideoStreamFramer::createNew(*m_env, m_videoES);
m_videoSink->startPlaying(*m_videoSource, nullptr, nullptr);
}
inline void doEvent() {
std::cout << "Doing event loop..." << std::endl;
m_env->taskScheduler().doEventLoop();
std::cout << "Done doing event loop" << std::endl;
}
inline void streamImage(const uint8_t* src, const int index) {
m_screenSource->encode(src);
}
I'm facing a very strange issue while interacting with mysql db through my c++ app.
environment:
docker-compose.yml
version: '3.1'
services:
db:
image: mysql:8.0.21 #libmysqlcppconn8-2_8.0.21-1ubuntu18.04_amd64.deb connector
command: --default-authentication-plugin=mysql_native_password
restart: always
environment:
MYSQL_ROOT_PASSWORD: example
security_opt:
- seccomp:unconfined
client:
build: .
ports:
- "2890:2890"
Client container is ubuntu18.04, here a simple code to test connection and a minimum result:
#include <cstdio>
#include <iostream>
#include <stdlib.h>
#include <unistd.h>
#include "mysql_connection.h"
#include <array>
#include <cppconn/driver.h>
#include <cppconn/exception.h>
#include <cppconn/prepared_statement.h>
#include <cppconn/resultset.h>
#include <cppconn/statement.h>
int main() {
sql::Driver *driver = get_driver_instance();
sql::Connection *con =
driver->connect("tcp://remote_backup_db_1", "root", "example");
con->setSchema("db_test");
sql::PreparedStatement *stmt;
sql::ResultSet *res;
stmt = con->prepareStatement("SELECT test from t;");
res = stmt->executeQuery();
if (res->rowsCount() > 0) {
if (res->next()) {
std::string text = res->getString("test");
std::clog << "text: " << text << "\n";
}
}
return 0;
}
here is a describe of the table:
+-------+--------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------+--------------+------+-----+---------+-------+
| test | varchar(128) | YES | | NULL | |
+-------+--------------+------+-----+---------+-------+
issue: when I try to retrieve a text that is less than 64 bytes everything works properly, but when I try to execute the same code with a text greater than 64 bytes it retrieves the firts 64 bytes followed by random characters. The problem seems not to be related to the column type (same problem with blob for example). It seems to be related with encoding because when i try to get the result length, it is set properly (e.g with a 70 character text long it gives me 70).
I've already tried to change table encoding and I don't know how to solve this. (ps I'm not using strange characters only ASCII basically).
Situation:
I'm attempting to get coverage reports on all python code in my current project. I've utilized Coverage.py with great success for the most part. Currently I'm using it like this taking advantage of the sitecustomize.py process. For everything that's being started from the command line, and it works amazing.
Issue:
I can't get python modules run from C++ via PyImport_Import() type statements to actually trace and output coverage data.
Example:
[test.cpp]
#include <stdio.h>
#include <iostream>
#include <Python.h>
int main()
{
Py_Initialize();
PyObject* sysPath = PySys_GetObject("path");
PyList_Append(sysPath, PyString_FromString("."));
// Load the module
PyObject *pName = PyString_FromString("test_mod");
PyObject *pModule = PyImport_Import(pName);
if (pModule != NULL) {
std::cout << "Python module found\n";
// Load all module level attributes as a dictionary
PyObject *pDict = PyModule_GetDict(pModule);
PyObject *pFunc = PyObject_GetAttrString(pModule, "getInteger");
if(pFunc)
{
if(PyCallable_Check(pFunc))
{
PyObject *pValue = PyObject_CallObject(pFunc, NULL);
std::cout << PyLong_AsLong(pValue) << std::endl;
}
else
{
printf("ERROR: function getInteger()\n");
}
}
else
{
printf("ERROR: pFunc is NULL\n");
}
}
else
std::cout << "Python Module not found\n";
return 0;
}
[test_mod.py]
#!/bin/python
def getInteger():
print('Python function getInteger() called')
c = 100*50/30
return c
print('Randomness')
Output:
If I manually run test_mod.py it outputs as expected. However, if I run the compiled test.cpp binary, it doesn't output anything for coverage data. I know sitecustomize.py is still being hit, as I added some debugging to ensure I wasn't going insane. I can also see in the coverage debug log that it does indeed want to trace the module..
[cov.log]
New process: executable: /usr/bin/python
New process: cmd: ???
New process: parent pid: 69073
-- config ----------------------------------------------------
_include: None
_omit: None
attempted_config_files: /tmp/.coveragerc
branch: True
concurrency: thread
multiprocessing
config_files: /tmp/.coveragerc
cover_pylib: False
data_file: /tmp/python_data/.coverage
debug: process
trace
sys
config
callers
dataop
dataio
disable_warnings: -none-
exclude_list: #\s*(pragma|PRAGMA)[:\s]?\s*(no|NO)\s*(cover|COVER)
extra_css: None
fail_under: 0.0
html_dir: htmlcov
html_title: Coverage report
ignore_errors: False
note: None
New Section 1 Page 2note: None
parallel: True
partial_always_list: while (True|1|False|0):
if (True|1|False|0):
partial_list: #\s*(pragma|PRAGMA)[:\s]?\s*(no|NO)\s*(branch|BRANCH)
paths: {'source': ['/tmp/python_source', '/opt/test']}
plugin_options: {}
plugins: -none-
precision: 0
report_include: None
report_omit: None
run_include: None
run_omit: None
show_missing: False
skip_covered: False
source: /opt/test/
timid: False
xml_output: coverage.xml
xml_package_depth: 99
-- sys -------------------------------------------------------
version: 4.5.4
coverage: /usr/lib64/python2.7/site-packages/coverage/__init__.pyc
cover_paths: /usr/lib64/python2.7/site-packages/coverage
pylib_paths: /usr/lib64/python2.7
tracer: PyTracer
plugins.file_tracers: -none-
plugins.configurers: -none-
config_files: /tmp/.coveragerc
configs_read: /tmp/.coveragerc
data_path: /tmp/python_data/.coverage
python: 2.7.5 (default, Jun 11 2019, 14:33:56) [GCC 4.8.5 20150623 (Red Hat 4.8.5-39)]
platform: Linux-3.10.0-1062.el7.x86_64-x86_64-with-redhat-7.7-Maipo
implementation: CPython
executable: /usr/bin/python
cwd: /opt/test
path: /usr/lib64/python27.zip
/usr/lib64/python2.7
/usr/lib64/python2.7/plat-linux2
/usr/lib64/python2.7/lib-tk
/usr/lib64/python2.7/lib-old
/usr/lib64/python2.7/lib-dynload
/usr/lib64/python2.7/site-packages
environment: COVERAGE_DEBUG = process,trace,sys,config,callers,dataop,dataio
COVERAGE_DEBUG_FILE = /tmp/cov.log
COVERAGE_PROCESS_START = /tmp/.coveragerc
command_line: ???
source_match: /opt/test
source_pkgs_match: -none-
include_match: -none-
omit_match: -none-
cover_match: -none-
pylib_match: -none-
-- end -------------------------------------------------------
<module> : /usr/lib64/python2.7/site.py #556
New Section 1 Page 3<module> : /usr/lib64/python2.7/site.py #556
main : /usr/lib64/python2.7/site.py #539
addsitepackages : /usr/lib64/python2.7/site.py #317
addsitedir : /usr/lib64/python2.7/site.py #190
addpackage : /usr/lib64/python2.7/site.py #152
<module> : <string> #1
process_startup : /usr/lib64/python2.7/site-packages/coverage/control.py #1289
start : /usr/lib64/python2.7/site-packages/coverage/control.py #690
_init : /usr/lib64/python2.7/site-packages/coverage/control.py #362
_write_startup_debug : /usr/lib64/python2.7/site-packages/coverage/control.py #382
write_formatted_info : /usr/lib64/python2.7/site-packages/coverage/debug.py #120
Not tracing '/usr/lib64/python2.7/threading.py': falls outside the --source trees
<module> : /usr/lib64/python2.7/site.py #556
main : /usr/lib64/python2.7/site.py #539
addsitepackages : /usr/lib64/python2.7/site.py #317
addsitedir : /usr/lib64/python2.7/site.py #190
addpackage : /usr/lib64/python2.7/site.py #152
<module> : <string> #1
process_startup : /usr/lib64/python2.7/site-packages/coverage/control.py #1289
start : /usr/lib64/python2.7/site-packages/coverage/control.py #701
start : /usr/lib64/python2.7/site-packages/coverage/collector.py #318
settrace : /usr/lib64/python2.7/threading.py #99
_trace : /usr/lib64/python2.7/site-packages/coverage/pytracer.py #111
_should_trace : /usr/lib64/python2.7/site-packages/coverage/control.py #593
[... Not tracing a bunch of common python code ...]
Tracing './test_mod.py'
<module> : ./test_mod.py #3
_trace : /usr/lib64/python2.7/site-packages/coverage/pytracer.py #111
_should_trace : /usr/lib64/python2.7/site-packages/coverage/control.py #593
I reproduced the issue using your code and you only forgot to call Py_Finalize(). As a result, the report is never generated whereas the data were collected.
It works with the following piece of code:
#include <stdio.h>
#include <iostream>
#include <Python.h>
int main()
{
Py_Initialize();
PyEval_InitThreads();
PyObject* sysPath = PySys_GetObject("path");
PyList_Append(sysPath, PyString_FromString("."));
// Load the module
PyObject *pName = PyString_FromString("test_mod");
PyObject *pModule = PyImport_Import(pName);
if (pModule != NULL) {
std::cout << "Python module found\n";
// Load all module level attributes as a dictionary
PyObject *pDict = PyModule_GetDict(pModule);
PyObject *pFunc = PyObject_GetAttrString(pModule, "getInteger");
if(pFunc)
{
if(PyCallable_Check(pFunc))
{
PyObject *pValue = PyObject_CallObject(pFunc, NULL);
std::cout << PyLong_AsLong(pValue) << std::endl;
}
else
{
printf("ERROR: function getInteger()\n");
}
}
else
{
printf("ERROR: pFunc is NULL\n");
}
}
else
std::cout << "Python Module not found\n";
Py_Finalize();
return 0;
PyObject *PySys_GetObject(char *name) returns a borrowed reference. Is not it the case that the reference count should be incremented? What about:
// ...
PyObject* sysPath = PySys_GetObject("path");
Py_INCREF(sysPath);
PyList_Append(sysPath, PyString_FromString("."));
Py_DECREF(sysPath);
// sysPath = NULL;
// ...
I'm only just starting with the Python-C API myself, but my understanding is that importing modules doesn't actually add them to your main module. You need to do that separately. I'm not sure if this will help with your issue, but my approach that's worked (minus the error checking) has been as follows:
// Initialize main module
PyObject* mainModule = PyImport_AddModule("__main__");;
// Initialize module to be added
PyObject* moduleNamePyObject= PyUnicode_DecodeFSDefault("moduleName");
PyImport_Import(moduleNamePyObject);
// Add module to main module
PyObject_SetAttrString(mainModulePtr, "moduleName", modulePyObject);
Normally, when importing a module, Python tries to find the module file next to the importing module (the module that contains the import statement). Python then tries the directories in “sys.path”. The current working directory is usually not considered. In our case, the import is performed via the API, so there is no importing module in whose directory Python could search for “test_mod.py”. The plug-in is also not on “sys.path”. One way of enabling Python to find the plug-in is to add the current working directory to the module search path by doing the equivalent of “sys.path.append(‘.’)” via the API.
Py_Initialize();
PyObject* sysPath = PySys_GetObject((char*)"path");
PyObject* programName = PyString_FromString(<DIRECTORY>.c_str());
PyList_Append(sysPath, programName);
Py_DECREF(programName);
If you are using python3 ,
Change PyString_FromString to PyUnicode_FromString.
Sources :
https://realmike.org/blog/2012/07/08/embedding-python-tutorial-part-1/
Python Embedding: PyImport_Import not from the current directory
I am creating a wrapper class for working with sqlite3 in a command-line C++ application on my macbook. The database connection only works once after compilation.
First, the wrapper class (cmodel::dbpath is defined in another header, and I output it in the constructor to be sure):
class dbconnect {
sqlite3 *db;
const char *dbname;
public:
dbconnect();
~dbconnect();
};
dbconnect::dbconnect() :
dbname(cmodel::dbpath) {
// Output the path
std::cout << this->dbname << std::endl;
sqlite3_initialize();
// initialize this->db
int state = sqlite3_open_v2(this->dbname, &(this->db), SQLITE_OPEN_READWRITE, NULL);
if(state == SQLITE_OK) {
printf("Database opened successfully\n");
} else {
printf("%s\n", sqlite3_errmsg(this->db));
}
}
dbconnect::~dbconnect() {
std::cout << "Destructor called" << std::endl;
sqlite3_close_v2(this->db);
sqlite3_shutdown();
}
The main() function
int main() {
dbconnect db;
return 0;
}
And here is my prompt
$ make
g++ -lpthread -ldl ... /Users/awesomeuser/bin/cmodel
$ cmodel # first run
/Users/awesomeuser/.cmodel/cmodel.db
Database opened successfully
Destructor called
$ cmodel # second run
/Users/awesomeuser/.cmodel/cmodel.db
unable to open database file
Destructor called
To be honest, I'm not a big fan of these specific questions, but I'm just baffled. Any idea why this is happening?
UPDATE:
Ok here's something extra which is happening. When I open the db in the mode SQLITE_READWRITE | SQLITE_CREATE (which creates the database if it doesn't exist), a new database is created titled cmodel.XTUM in the same directory as cmodel.db. Does this sound familiar?