How to call C++ DLLs from C#

Most of my code is in C#, but I occasionally encounter functionality that is only available in a C++ DLL. Luckily, it is possible to call C++ DLLs from C#, the main challenge being the difference in data types. It’s usually advisable to build a wrapper around the C++ functionality that you need so you can go with very simple function calls. In my case, I have to read points from a file in Riegl RDB format using Riegl’s RDBlib library. If this were pure .Net code, one could simply go through the file and add each point to a C# List object. But since this is a C++ library, it has to be done differently. I first need to get the number of points, then size the arrays for the data accordingly, and then read the points. Hence I end up with two functions in my C++ wrapper DLL, heres the header content:

#pragma once
#define RDBLIBWRAPPER_API __declspec(dllexport)
#define RDBLIBWRAPPER_API __declspec(dllimport)
extern "C" RDBLIBWRAPPER_API int readpofx_header(const char* filename, int *n);
extern "C" RDBLIBWRAPPER_API int readpofx(const char* filename, double *time, double *rdx, double *rdy, double *rdz, double *roll, double *pitch, double *yaw);

The first function returns the number of points, which is then used to size the arrays, e.g.

double[] time_array = new double[n];

The calls to the DLL functions are defined as follows in the C# code:

[DllImport("RDBlibwrapper.dll", EntryPoint = "readpofx_header", CallingConvention = CallingConvention.StdCall)]
public static extern int Readpofx_header(string filename, out int n);
[DllImport("RDBlibwrapper.dll", EntryPoint = "readpofx", CallingConvention = CallingConvention.StdCall)]
public static extern int Readpofx(string filename, double[] time, double[] rdx, double[] rdy, double[] rdz, double[] roll, double[] pitch, double[] yaw);

They can then be called like this, where filename is a C# string:

int status = Readpofx_header(filename, out n);
int status = Readpofx(filename, time_array, x_array, y_array, z_array, roll_array, pitch_array, yaw_array);

You need to make sure that Windows can find all DLLs, also those that are depended upon by others. You can use the tool Dependency Walker to find out the dependencies a DLL has.

Schreibe einen Kommentar

Deine E-Mail-Adresse wird nicht veröffentlicht. Erforderliche Felder sind mit * markiert