python & hoc strings

When Python is the interpreter, what is a good
design for the interface to the basic NEURON

Moderator: hines

Post Reply
Posts: 15
Joined: Sun Dec 12, 2010 1:14 pm

python & hoc strings

Post by samnemo »

I am trying to modify a hoc string from within a mod file (strtest.mod code below) and want to be able to do this using both hoc and python. When I call the code in there's no error when running using NEURON h(command) syntax, but when using h.variablename syntax, I get an error. Although the type of h.tstr (from the code below) is a python string (<type 'str'>) and therefore immutable, is there a way to get access to the hoc strdef via h.variablename syntax without h.variablename making it a python string?

Thanks for any tips...

strtest.mod (compile with nrnivmodl):

Code: Select all

  SUFFIX nothing
PROCEDURE strtest () {
  char **pname, str[100];
  char** hoc_pgargstr();
  pname = hoc_pgargstr(1);
  printf("first pname is %s\n",*pname);
  printf("now pname is %s\n",*pname);
} (run special -python, or import test):

Code: Select all

from neuron import h

print "------------------------------------------------"
print "                STARTING TEST"
print "------------------------------------------------"

h("strdef tstr") // declare the string in hoc
print "first, from hoc:"
h("strtest(tstr)") // run the test in hoc -- works properly

print type(h.tstr) # <type 'str'>

print "next, from python:"
h.strtest(h.tstr) # run the same thing from python -> causes a crash
NEURON source code in src/oc/code.c where the crash occurs:

Code: Select all

hoc_assign_str(cpp, buf)
	char** cpp, *buf;
	char* s = *cpp;
	*cpp = (char *)emalloc((unsigned)(strlen(buf) + 1));
	Strcpy(*cpp, buf);
	if (s) {
		hoc_free_string(s); // this line causes the crash

Site Admin
Posts: 1598
Joined: Wed May 18, 2005 3:32 pm

Re: python & hoc strings

Post by hines »

The following fragment from ... essing_Hoc

Many hoc functions use call by reference and return information by changing the value of an argument. These are called from the python world by passing a HocObject.ref() object. Here is an example that changes a string.

h('proc chgstr() { $s1 = "goodbye" }')
s = h.ref('hello')
print s[0] # notice the index to dereference. prints hello
print s[0] # prints goodbye
h.sprint(s, 'value is %d', 2+2)
print s[0] # prints value is 4

Post Reply