I need to use the C library in a C# project. How can I do?
To be more specific: for reasons of efficiency I need to use the strtod function to extract double values from a string (like this “9.63074,9.63074 -5.55708e-006 0 ,0 1477.78”). If you have suggestions about how to optimize this operation do not be shy, but the main question remains that specified by title.
I think it very unlikely that p/invoking to
strtodwould be more efficient than a pure C# solution. There is an overhead in managed/unmanaged transitions and I would think that would be significant for something as trivial asstrtod. Myself I would use a C# tokenizer, combined withdouble.Parse.The simplest C# tokenizer is
String.Split()which yields this routine:However, since I enjoy p/invoke, here’s how you would call
strtodfrom C#, bearing in mind that I recommend you don’t use this approach in real code.You can call it like this:
I’m passing the string as an
IntPtrbecause you would be callingstrtodrepeatedly to walk across the entire buffer. I didn’t show that here, but if you are going to make any use ofendptrthen you need to do it as I illustrate.Of course, to use
strtodremotely effectively you need to gain access to theerrnoglobal variable. The very fact that you need to deal with a global variable should be warning enough that here be dragons. What’s more, the error reporting offered througherrnois exceedingly limited. However, if you want it, here it is:One final point. Your suggested input string is
but
strtodwon’t tokenize that because of the spurious commas.