5
\$\begingroup\$

For interop purpose, this is something that I always do (C#):

 public static extern BigObject InteropWithCPlusPlus();

where BigObject is ( you guess it) a big object, it's not something small like int, or double.

Now, is this a good practice? Or is it better to do the interop in this way:

public static extern void InteropWithCPlusPlus(ref BigObject bigObject);

I prefer the first one as it is easier to read and understand, but I afraid that it comes with performance penalty when the return object is a large, consuming memory one.

\$\endgroup\$
2
  • \$\begingroup\$ This site is for reviewing code (which means we should see some code and implementation in the question). The question above is asking about best practices, which seems more in line with Programmers.SE. \$\endgroup\$ – Mark Loeser Feb 9 '11 at 16:28
  • 1
    \$\begingroup\$ Mark may be right, though I think reviewing adherence to best practices in a block of code is part of the game this is more like a straight up question. Since we're all here: I don't believe there's any difference in the marshaling strategy .NET will use so there's likely no performance difference which makes your preference fit the pattern of .NET code more, but are the native libraries used by other stuff too? If so perhaps you should apply whatever the best practice is to your native library and handle the usage style differences in your managed wrapper. \$\endgroup\$ – TheXenocide Feb 9 '11 at 17:46
4
\$\begingroup\$

I don't think there would be too much of a difference. You have to use a reference anyway, because non-native types are stored as references. On x86 processors, returns are placed in register A, which is limited length. So, your C++ program would be either returning a reference to BigObject or modifying an existing instance of it.

The area where I can see a performance hit is in memory allocation. If you are making that call, using the object, and then discarding it, it would be faster to create on single instance in your C# code and use that rather than allocating memory every time. You'll get diminishing returns for small numbers of calls, though; unless you have a couple thousand in a given program run, you probably won't notice the hit either way.

\$\endgroup\$
2
  • \$\begingroup\$ On x86 processors, returns are placed in register A, which is limited length-- I guess you are saying that my method 1 cannot return too big an object? \$\endgroup\$ – Graviton Feb 10 '11 at 1:36
  • \$\begingroup\$ Not by value. Objects bigger than the register have to be passed by reference, because while the register is too small for the value, it is big enough for a memory address. \$\endgroup\$ – Michael K Feb 10 '11 at 13:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.