1

I believe lot of people already asked this question before, but i kept getting confused more and more. I am looking for a answer in layman's terms. I have a c++ library to perform one action. I need to call the functions from this library from my C# program. What is better way to do this and why? whether pinvoke from C# app or write a wrapper in C++/CLI.

There is only 1 function in C++ library (ReadNextRecord) which will be called from C# program. C# program should first create object of class defined in C++ library and then call a function to get the next record from a data source. Function is called many times ( >50000 times) so efficiency is an issue.

In most documents I see how to wrap a function to call from C# code. I dont see more complicated example where a c++ object is created in C# space and then a func is called on the object.

Please advice.

Regards, Alok

Alok
  • 3,160
  • 3
  • 28
  • 47
  • 2
    You can't pinvoke a non-static method of a C++ class, C++/CLI is required. http://stackoverflow.com/questions/2691325/c-cli-mixed-mode-dll-creation – Hans Passant Dec 27 '11 at 08:53
  • Remember to use some form of batching to speed up the interop. 50.000 calls can result in a lot of overhead. while transferring 10.000 records at a time won't have much overhead. – CodingBarfield Dec 27 '11 at 11:24
  • thanks. i will try to group the records while returning. will have to change the design a bit. – Alok Dec 27 '11 at 13:33
  • @HansPassant i have the code for the library and i can change it the way i want. what do you suggest is better way from the performance point of view? – Alok Dec 27 '11 at 13:33
  • Why do you assume you have a perf problem? "get the next record from a data source" is something that no doubt involves I/O. Which is orders of magnitude slower than any code you'd write. Measure, don't assume. – Hans Passant Dec 27 '11 at 15:15
  • say I/O takes x amount of time. If we assume that this remains constant, then which approach is faster to deal with this data PInvoke or CPPCLI? I need to read the data as fast as possible. We cannot control the I/O but we can definitely control the way to deal with this data? – Alok Dec 28 '11 at 00:56

1 Answers1

3

When dealing with C++ code, it is easier to use C++/CLI (at least, assuming you are working with the source code for the C++ library or at least know it is compiled with MSVC, C++ is not ABI-compatible across compilers in general). PInvoke is mostly useful for C functions, but can be made to work with some C++ functions (see this question).

Community
  • 1
  • 1
Krumelur
  • 31,081
  • 7
  • 77
  • 119
  • thanks.I have the code for the c++ library and i can change it if needed. I will write the c++/CLI wrapper for the c++ library and call the functions from the C# application using the wrapper. – Alok Dec 27 '11 at 13:34