Problem in Accessing C++ Class Instance Global Variable (near success, help please!!)

Bjorn Pettersen BPettersen at NAREX.com
Fri Apr 18 10:15:37 EDT 2003


> From: Alan Pong [mailto:alanpong at hkstar.com] 

Plase be considerate to people who've been up all night and has to go
through your entire reply to get the context. The expected form almost
everywhere is quote what you're talking about, type your
question/answer, repeat until done, and delete everything else. Like I'm
doing here :-)

> > First, PyImport_AddModule( "myext1" ), doesn't load the module [...]
> >
> 1. i did used Py_InitModule.

Please study the manual (e.g. look up what it says the two functions
above do). This topic has too many details to teach introductions here
without rewriting the manual. FWIW, you want something close to:

  Py_Initialize();

  PyObject* mainmod = PyImport_AddModule("__main__");
  m_namespace = PyModule_GetDict(mainmod);
  Py_INCREF(m_namespace);

  PyObject* nrx = PyRun_String("import nrx\n", Py_file_input,
m_namespace, m_namespace);

  if (nrx == NULL) {
    throw new NException(getTraceback().c_str(), 25, __FILE__, 0);
  } else {
    Py_DECREF(nrx);
  }

  FILE* fp = fopen("test.py", "r"); // you seem to have missed this
step?
  PyObject* result = PyRun_File(fp, "test.py", m_namespace,
m_namespace);
  etc., etc.

> > The symptoms imply that your "library" (wrapper.cpp) is most likely
> > compiled statically against both your program (test.exe) and your
dll
> > (myext1.cpp). [...explanation why that's two different 'varables' at
> > runtime...]
> >
> 2. correction: wrapper.cpp compiled to wrapper.obj which is linked to
> form myext1.dll.   test.exe doesn't contain wrapper.obj

Then there is something horribly wrong with what you sent us. If
wrapper.cpp and myext1.c are compiled to object files, there is an
external reference to gtest in wrapper.obj. The linker must find it
somewhere to be able to create a dll. Either you're also linking in
test.cpp with the dll (the only file with a defintion of gtest),
resulting in what I described above, or your code and the code in the
email are different.

> > fix1: "Don't do that" <wink>.
> > fix2: pass the object as an argument.
> >
> 3.  sorry i don't understand fix2 and fix3 mentioned below.

#1 Global variables are considered a bad solution to most problems,
usually when you think you _have_ to have it, there is a better and
simpler way.

#2 One way of not referencing a global G in function f is to pass G as
an argument to f.

> 4. i re-think about: can i access a global variable like this???? ...
> 
> any sample code please?

These are really very fundamental C and dll issues you're dealing with
(by now you should have checked the address of gtest when you're in main
and when you're in SetString etc.). I wouldn't know where to start
helping you without rewriting your program in some form, and I doubt
that will help very much...?

-- bjorn






More information about the Python-list mailing list