From: Klaus K. <kk...@su...> - 2013-12-16 13:27:49
|
* Macumber, Daniel <Dan...@nr...> [Dec 14. 2013 06:51]: > > However, I cannot call this function like: > > funcOnlyTakesAPath("./here") > > How can I get SWIG to allow implicit conversion of std::string to path? Daniel, you need to set up an 'input typemap' in your SWIG .i file as follows %typemap(in) const path& path_from_string { /* typemap body */ } The typemap signature (type and name of the input parameter) must match the signature of funcOnlyTakesAPath(). You can get along with just specifying 'const path&', but it would also match all other functions accepting const path& as parameter. This might be wanted or unwanted. Inside the typemap(in) body, the input parameter to the typemap is referenced by $input. The output parameter from the typemap (which is the input parameter to funcOnlyTakesAPath()) is named $1. When creating Ruby bindings, $input is of type VALUE (raw Ruby value), $1 must be of type const path. The full input typemap (following Bob's example) could look like this %typemap(in) const path& path_from_string { switch (TYPE($input)) { /* convert nil to empty path */ case T_NIL: $1 = new path(""); break; /* string value passed */ case T_STRING: $1 = new path(StringValuePtr($input)); break; /* non-string passed: call to_s to get string representation */ else VALUE input_s = rb_funcall($input, rb_intern("to_s"), 0 ); $1 = new path(StringValuePtr(input_s)); } } This typemap should work for all Ruby types which have a reasonable string representation, like e.g. Pathname. The need for a %typemap(freearg) as outlined in Bob's mail depends on how your path() constructor treats its input arguments. If it copies its input (which it should), then the freearg is needed to prevent memory leaks. If the constructor uses the pointer as-is, the freearg would free a pointer still in use by the path object. Hth, Klaus -- SUSE LINUX Products GmbH, GF: Jeff Hawn, Jennifer Guild, Felix Imendörffer, HRB 16746 (AG Nürnberg) Maxfeldstraße 5, 90409 Nürnberg, Germany |