How to share primitive data between C# and C++? - c#

Let's say I have some int sharedInt that I need to share between managed C# code and a native C++ library. Both the C# and C++ code need to be able to read and write from/to sharedInt.
My first solution was to allocate memory from C# using Marshal.AllocHGlobal(), pass the IntPtr to the C++ library as an int*, and read/write to it using Marshal.ReadInt32() and Marshal.WriteInt32(). This worked, but the constant Marshal calls slowed my application quite a bit.
My second solution was to simply declare the int from C#, pass it as a ref int to the C++ library, and read/write from it directly. This works for the first few calls, and then behaves unpredictably, often throwing an ExecutionEngineException. Maybe the garbage collector is at fault?
How do I accomplish my goals? How do references to value types work in C#? Do I need to create some wrapper structure, and how do I properly pass it to C++?

Related

How to pass an array of structs from c++ to c#?

I have been researching this for a while but can not find a solution.
I am writing a program that is using a c++/CLI wrapper. My goal right now is to return a list of all running processes and their PID (among other information) to c#. I have a running C++ function that returns a vector of type PROCESSENTRY32, but don't have the slightest clue how to get that information to c#.
I know there is a function in c# to get all running processes, but I'm trying to do it in c++.
Any tips or pointers in the right direction would be great.
First, set up an api for your c# application to access data from. Declare your API functions with __declspec(dllexport) just before your C++ functions return type. Using a #define for this can be handy.
In C# land, make sure you have using System.Runtime.InteropServices; Then, make a static method handle for your api using [DllImport("dll_name.dll", CharSet = CharSet.Unicode)] method attribute for your method then static extern returnType CallCPPFunction(); You'll have to write a custom data parser using this method as the returned data is simply a bunch of bytes (Meaning C# will attempt to cast the received data from C++ as the return type you specify in C#). You could make a struct in C# constructed with a byte array, and set that as the constructor parameter, however, you can make your job a lot easier by sending one or more int* as parameters to the C# function that hold useful data like sizeof(object) or significant markers in the objects data to make parsing it easier. Keep in mind the memory here is simultaneously managed by C# and C++, so if you pass an int* holding the sizeof(object) you'll still need to delete that pointer in C++, but make sure you don't do stuff like that when C# or C++ is still using the data. You could do some unsafe code in C# where C++ passes a bool* that starts as false, then C# marks it as true when it's done reading the data.
I'm not an expert in this Marshalling business, but I have successfully used this exact method of transferring data in this manner in the past. It's entirely possible there's some way to use the C++ types in C# so that this data parsing isn't necessary, or C# somehow using the .h files to do stuff, but if there is, I don't know it. Here's the tutorial that I watched to figure out the concept myself, but it's a bit long and I couldn't find another one that was the same thing I was looking for:
https://www.youtube.com/watch?v=w3jGgTHJoCY
If I'm not mistaken, the data parsing won't even be necessary if you re-create the C++ struct in C# such that the first data member defined is the same associated data member in the C# struct, second C++ member to the second in C# etc. Keep in mind the size of the data types needs to match, or the data will be offset once it hits a data member whose size in C++ and C# don't match. If your struct contains sub-types you'd need to re-create those in C# too; all the way down to the primitive type level.

C# dllimport'ing complex datatypes across platforms?

So I'm writing a wrapper in C# for a C dll. The problem is several of the functions use complex datatypes e.g.:
ComplexType* CreateComplexType(int a, int b);
Is there a way I can declare a valid C# type such that I can use dllimport?
If I were doing a Windows-only solution I'd probably use C++/CLI as a go-between the native complex type and a managed complex type.
I do have access to the source code of the C dll, so would it be possible to instead use an opaque type (e.g. handles)?
Such a function is difficult to call reliably from a C program, it doesn't get better when you pinvoke it. The issue is memory management, that struct needs to be destroyed again. Which requires the calling program to use the exact same memory allocator as the DLL. This rarely turns out well in a C program but you might be lucky that you have the source code for the DLL so you can recompile it and ensure that everybody is using the same shared CRT version.
There is no such luck from C# of course, the pinvoke marshaller will call CoTaskMemFree() to release the struct. Few real C programs use CoTaskMemAlloc() to allocate the struct so that's a silent failure on XP, an AccessViolationException on Vista and higher. Modern Windows versions have a much stricter heap manager that doesn't ignore invalid pointers.
You can declare the return value as IntPtr, that stops the pinvoke marshaller from trying to destroy it. And then manually marshal with Marshal.PtrToStructure(). This doesn't otherwise stop the memory leak, your program will eventually crash with OOM. Usually anyway.
Mono has a good documentation page on using P/Invoke in Windows vs. Linux. Specifically, see the section on marshaling, that discusses simple vs. complex types. If you want to get creative, you could serialize your type to some convenient string-based format like JSON or XML and use that as your marshaling mechanism.

Calling native DLL functions that return (and accept) pointers to structs

I've got a "native" DLL with some nice functions that can return (and accept) pointers to data which is formatted according to particular C structs.
In my C# program I don't care about the struct internals, I just want to get and pass them from/to the native functions. I've already managed to pinvoke the functions inside the DLL.
For to pointers, I've thought of using void* (as a "pointer-to-unknown"), since I really don't care the internal fields of the pointed structs, I just need to store and use the pointers to pass it to the DLL library functions.
But using void* for many different kinds of data makes my code unreadable! Is there any way in C# to typedef void* some_nicer_type_t ? Or to do something like that?
You could consider using IntPtr instead.
From MSDN:
A platform-specific type that is used
to represent a pointer or a handle.
This may ultimately aid you in writing non-unsafe code, too.
EDIT:
To address your desired needs as reiterated in comment to this question, one thing I might suggest (though not proposing this to be ideal) is to define a struct or class which is essentially a wrapper around a pointer:
public struct TypedPointer
{
public IntPtr UnderlyingPointer;
}
As you yourself bring up, this may lead to wrapping even more code in order to have it all conform to the usage and aesthetics of usage that you want.
IntPtr
is the way to go.
Only area which you have to be careful is the memory management. Unsafe or not - C# needs a reference otherwise it will be sooner or later garbage-collected - potentially also when one of the external dlls uses it. Thus you need to ensure that the reference to the IntPtr is kept as long as needed also on the C# side.

Passing a structure of data from VC++ to C#?

I want to transfer a structure of data to an application which is created in C#.
I will be filling the structure in a VC++ program.
How can I send it?
Is structure suppported in C#?
Or else if I use LPDATA in VC++: how can I get the same thing in C#?
Defining the struct in C#
When defining your struct in C# make sure you use datatypes which match the C++ implementations. Char in C++ as Byte in C# etc...
You need to add some attributes to ensure your struct memory layout in C# matches the C++ implementation
[StructLayout(LayoutKind.Sequential, Size=TotalBytesInStruct),Serializable]
public struct MyStruct
{
}
Passing the struct
Declare a struct in C# using the same data structure. Pass a pointer to the struct to your C# app from C++ and cast it to the new struct in C#.
Calling you C# dll
For calling your C# DLL, your best option is to use a mixed mode assembly in C++. This allows you to use the pragmas managed and unmanaged to switch between native and managed code. This way you can nicely wrap you C# class with a workable C++ wrapper. See this Microsoft article. Be aware though, this is not supported on Mono.
Yes, structure is supported and can be used. Strings may require a bit of work, however.
Show us your structure. C# has marshaller helpers to map its types to native c++ types easily, you just have to know how to decorate your types, and we can help with that if you show us your structure.
For example, that LPDATA thing you mentioned, if that's char *, it maps directly over byte[] in C# if it's a generic buffer, or string if it's a normal string (the string mapping requires marshaller help, but it's a lot easier to use once decorated properly).
You could learn a lot from the "platform invoke tutorial" on MSDN.
The only difference is that you'll be invoking your own DLL :)

tStringList passing in C# to Delphi DLL

I have a Delphi DLL with a function defined as:
function SubmitJobStringList(joblist: tStringList; var jobno: Integer): Integer;
I am calling this from C#. How do I declare the first parameter as a tStringList does not exist in C#. I currently have the declaration as:
[DllImport("opt7bja.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public static extern int SubmitJobStringList(string[] tStringList, ref int jobno);
But when I call it I get a memory access violation exception.
Anyone know how to pass to a tStringList correctly from C#?
You'll most likely not have any luck with this. The TStringList is more than just an array, it's a full-blown class, and the exact implementation details may differ from what is possible with .NET. Take a look at the Delphi VCL source code (that is, if you have it) and try to find out if you can rebuild the class in C#, and pass it with the help of your best friend, the Interop Marshaller. Note that even the Delphi string type is different from the .NET string type, and passing it without telling the marshaller what he should do, he will pass it as a char-array, most likely.
Other than that, I would suggest changing the Delphi DLL. It's never a good thing to expose anything Delphi-specific in a DLL that is to be used by non-Delphi clients. Make the parameter an array of PChar and you should be fine.
If this is your DLL, I'd rewrite the function to accept an array of strings instead. Avoid passing classes as DLL parameters.
Or, if you really want to use a TStringList for some reason, Delphi's VCL.Net can be used from any .Net language.
An old example using TIniFile: http://cc.codegear.com/Item/22691
The example uses .Net 1.1 in Delphi 2005. Delphi 2006 and 2007 support .Net 2.0.
If you don't control the DLL and they can't or won't change it, you could always write your own Delphi wrapper in a separate DLL with parameters that are more cross-language friendly.
Having a class as a parameter of a DLL function really is bad form.
I am not exactly clear your way of using delphi and C#. It seems you have created a Win32 DLL which you want to call from C#. Offcourse you must be using PInvoke for this.
I would suggest that you create a .NET DLL using your source code since complete porting of VCL is available. I can further elaborate if you wish....
In theory, you could do something like this by using pointers (casting them as the C# IntPtr type) instead of strongly typed object references (or perhaps wrapping them in some other type to avoid having to declare unsafe blocks), but the essential catch is this: The Delphi runtime must be the mechanism for allocating and deallocating memory for the objects. To that end, you must declare functions in your Delphi-compiled DLL which invoke the constructors and destructors for the TStringList class, you must make sure that your Delphi DLL uses the ShareMem unit, and you must take responsibility for incrementing and decrementing the reference count for your Delphi AnsiStrings before they leave the DLL and after they enter it, preferably also as functions exported from your Delphi DLL.
In short, it's a lot of work since you must juggle two memory managers in the same process (the .NET CLR and Delphi's allocators) and you must both manage the memory manually and "fool" the Delphi memory manager and runtime. Is there a particular reason you are bound to this setup? Could you describe the problem you are trying to solve at a higher level?
As Hemant Jangid said, you should easily be able to do this by compiling your code as a .NET dll and then referring to that assembly in your c# project.
Of course, you'll only be able to do this if the version of Delphi you have has Delphi.NET.
I don't know a lot about c#, but a technique that I use for transporting stringlists across contexts is using the .text property to get a string representing the list, then assigning that property on "the other side".
It's usually easier to get a string over the wall that it is a full blown object.

Categories