[Gtk-sharp-list] pinvoke and benchmarks

Michael Hutchinson m.j.hutchinson at gmail.com
Tue Sep 16 23:02:59 EDT 2008

On Fri, Sep 12, 2008 at 11:22 AM, Martin (OpenGeoMap)
<martin at opengeomap.org> wrote:
> Hi:
> Someone knows about the performance in a library used only with c# or
> used thanks to other C API???
> I am working in a bindings to mono and .NET in c# for lidar data and i
> see my program really really slowly in relationship with the C API.
> We have created a C++ libvrary and a C API to used it with mono and python:
> http://liblas.org/
> is it better used a library only created with C or the pinvoke is fast???
> In my imagination i see the pinvoke system trying to find a funtion
> every time and if i have 10 million of lidar data perhaps this is really
> slowly....

The function lookup will only take place once for each function, so
you don't need to worry about that. However, AFAIK P/Invoke will cost
you somewhere around 50 cycles each time you cross the
managed/unmanaged boundary (for handling the managed stack,
exceptions, thread aborts etc), plus whatever it takes to marshal the
data strcutures in the arguments/return values. For this reason, you
should minimise managed/unmanaged transitions. It's often much faster
if you reimplement smaller methods in C#.

Another trick is zero-marshalling P/Invoke -- with a single call you
can pass over an IntPtr to a struct, then use unsafe (but still C#)
code to dereference and access the struct 's members directly. Note
that this only works for value types, i.e. not classes.

Looking at your LASPoint class, it looks like accessing every
property's getter/setter would cause a managed/unmanaged/managed
transition. If this is your primitive data type, it might be better to
use a struct for the LASPoint in the C API.

I imagine you'd get the best performance (and API) just by porting all
of libLAS to C#...

> Perhaps the C++ managed language is better than c# to create bindings:
> http://msdn.microsoft.com/en-us/library/ms235281(VS.80).aspx
> , but i don´t see the c++ in mono....
> http://www.mono-project.com/Languages

There are a number of issues with implementing C++/CLI for Mono.
Firstly, implementing a C++ compiler isn't easy. Also, C++/CLI
normally produces "mixed-mode" assemblies that contain managed *and*
unmanaged code. Unmanaged code, of course, is not portable across
platforms. Mono can handle mixed-mode assemblies, but *only* on
Windows (or Wine).

Another option would be to use the MS C++/CLI compiler to generate
"verifiable" managed assemblies:
http://msdn.microsoft.com/en-us/library/85344whh(VS.80).aspx In theory
these would run on Mono, since they cannot contain any unmanaged code.
As with porting the C++ code to C#, this might well be the fastest
option. You could even decompile it to C# using reflector ;-)

Michael Hutchinson

More information about the Gtk-sharp-list mailing list