Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a memcmp equivalent for comparing byte arrays in Mono?

There is a well-known efficiency for comparing two byte-arrays in .Net by importing the memcmp function from msvcrt.dll, as described here.

Is there an equivalent library import in mono? Would it need to be different when running mono on linux or on windows? Or is there another fast byte array comparison technique that works well in mono? I'm looking for something better than just iterating over the arrays in c#.

Update

Based on Matt Patenaude's comment, I think this might work well:

#if __MonoCS__
    [DllImport("c", CallingConvention = CallingConvention.Cdecl)]
#else
    [DllImport("msvcrt.dll", CallingConvention = CallingConvention.Cdecl)]
#endif
    public static extern int memcmp(byte[] b1, byte[] b2, UIntPtr count);

But I have not yet tried it. I've never done p/invoke on mono before. I'm using the signature recommended on pinvoke.net. Is this going to be compatible?

Looking for a Mono-focused answer. Thanks.

like image 740
Matt Johnson-Pint Avatar asked Dec 17 '12 23:12

Matt Johnson-Pint


2 Answers

Based on your update, you shouldn't be using the __MonoCS__ preprocessor. It means you would have to recompile the library for Mono and .NET. The better way is to use dllmap functionality in Mono and only use the msvcrt.dll DllImport.

Instead define a "AssemblyName.dll.config" and use the dllmap tag to map msvcrt.dll to c when run on Mono.

Example:

<configuration>
    <dllmap dll="msvcrt.dll" target="libc.so.6" />
</configuration>

More detail on dllmap here: http://www.mono-project.com/Config_DllMap

EDIT

And if for some reason c doesn't work, libc.so should work.

like image 66
Robert Rouhani Avatar answered Nov 02 '22 07:11

Robert Rouhani


You can use unsafe code blocks to access byte arrays almost as fast as native memcmp. Before you go down that road, make sure a straight for loop isn't fast enough for your purposes.

like image 31
Ben Avatar answered Nov 02 '22 07:11

Ben