python & hoc strings

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

Moderator: hines

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

python & hoc strings

Post by samnemo » Tue Jun 26, 2012 1:39 pm

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 test.py 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 test.py 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

NEURON {
  SUFFIX nothing
}
PARAMETER {
}
ASSIGNED {
}
PROCEDURE strtest () {
  VERBATIM
  char **pname, str[100];
  char** hoc_pgargstr();
  pname = hoc_pgargstr(1);
  sprintf(str,"goodbye");
  printf("first pname is %s\n",*pname);
  hoc_assign_str(pname,str);
  printf("now pname is %s\n",*pname);
  return;
  ENDVERBATIM
}
test.py (run special -python test.py, 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
	}
}

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

Re: python & hoc strings

Post by hines » Wed Jun 27, 2012 12:17 am

The following fragment from

http://www.neuron.yale.edu/neuron/stati ... 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
h.chgstr(s)
print s[0] # prints goodbye
h.sprint(s, 'value is %d', 2+2)
print s[0] # prints value is 4

Post Reply