There's more than one way to do things | |
PerlMonks |
comment on |
( [id://3333]=superdoc: print w/replies, xml ) | Need Help?? |
My previous post covered one way of "how to do it". This is a separate post because the focus is on "why are you doing that?" and a re-coding of your original code.
I did some bit of "mind reading" and re-coded your C function. It looks like you wanted 2 different ways for your function to return the result? If you gave it a "ret string", you wanted that string modified "in place"? Otherwise you wanted a new result to be passed to $output? Very confusing to me. Please un-confuse me. Anyway, I don't see the need for this "ret" input parm at all. Take in a string, do something that generates another string and return that string. What is the need for this second input string? It is possible to modify a string "in place", but that would require the caller to provide enough memory so that when the string becomes longer, it does not overflow allocated memory. I have no idea about the details of your string transformation equation - I leave that detail to you. Here is my version below. There is one way to get the input and one way to get the output.
It is apparent that the malloc'ed memory gets passed as an SV to $output. At that point, I don't know for sure how this works, but Perl would have to be responsible for calling "free()" on that pointer when the memory for $output is not needed anymore. I didn't allocate more memory than needed, but that detail doesn't matter much. What does matter is not "re-using memory in a way that is opaque to the user". That is what your version with "static" would do. I recommend against that. Update: Geez, I am updating a lot tonight. My brain is working on a different project at the moment...But the thought does occur that I don't see anything in this code that would warrant a C subroutine (there is no performance issue). If you explain more about the string transformation algorithm, I am confident that this could be written in native Perl code. In my testing, it does take some extra time to invoke the C compiler and any generated messages are a bit harder to understand than it would be with a native C program. A "pure Perl" implementation would start faster and run time would make no difference. But I get it that you are playing with various options of passing parameters and getting results. Well as I continue to learn...Update...it is not necessary to do this malloc() stuff...it is possible to create/allocate memory for a new SV string object in one C statement as shown below. This stuff is complex. To say the least!
In reply to Re: Inline::C and NULL pointers
by Marshall
|
|