Can I use C headers for protocol in C# - c#

I've got technical problem with a new C# program I'm developing.
In this project I need to communicate with another none windows based system on a TCP/IP network.
Al the software written on the other system is done in C and any other future development will be done in C/C++ aswell.
The protocols are all done in C by another engineer and definitions of the protocols are all done using C typedef struct's defining all the variables and using memcpy to extract/put the data packets which works fantastic for C.
All my protocols are supplied as C header files with all the typedef and struct's in them and any changes made to the protocol in the future will be done in the same way.
My question is, if there is any way to use them in C#?
I've tried to compile them as a class into a DLL library but not working cause C# can only use managed C dll's. If I try and compile as managed C class, it just becomes a mess due to the fact that there are many arrays in the protocol and because the C code has to conform to a bunch of mill specs, many of the variables have been typedef'd. Now I could go and redo all the structures in C# but that's going to take a lot of time and I'm going to have to redo it every time a change is made or something added to protocol. Not even to mention the danger of errors slipping in every time I do it.
How it worked with my C projects is that the other engineer would just supply me with the updated header files.
So is there any way to use those header files directly in C# or a automated conversion I can do every time the protocol is updated?
Well I basically need to use this header file to extract the data from the data stream coming over the TCP/IP connection (without begin able to use memcpy)
Reason for using C# is because I use a lot of graphics in WPF and Visual C++ doesn't support WPF
Any help or suggestions would be much appreciated?

I've once had to use C headers in C# to get definitions of marshalled structures sent via TCP/IP. The approach we used was parsing the header files by T4 Text Template. It's a somewhat lenghty task though, you have to write C parser good enough for your headers and use it to produce .cs file, so there is a lot of string mess. For us, it was a good enough solution, so it may help you as well.
Have a look at T4 here: http://msdn.microsoft.com/en-us/library/bb126445.aspx

Not really an answer, more like one possible good solution:
Create a defintion file containing the information now in C header file. Then use that to generate both the .h header and suitable C# source code.
If the data is fairly simple, then also simple key-value file format, or even a csv file, could be used. But if it's more complex, then it's best to use XML, which is simpler to parse programmatically.
If there is resistance to having a language-independent definition file, then you could try to get the .c header file to follow some string formatting rules, so you can parse it simply and generate C# code from it (just make sure that the one writing the .h understands, that it is no longer C, it's actually your own C-like definition language, and any extra C stuff has to go to another file).

You don't and can't use a header file in C# you you need to compile it into dll and from c#
in the c File you need to define #define DLLAPI __declspec(dllexport) and define the methods like like the following DLLAPI *return-value-data-type function-name*
and from c# you need to call it like below
[DllImport(#"*dll-path*")]
public static extern *return-value-datatype function-name*
and if it is needed you do marshalling for datatypes like the following
[DllImport(#"*dll-path*")]
public static extern void InitParam([MarshalAs(UnmanagedType.LPWStr)] string inputFile,
[MarshalAs(UnmanagedType.LPWStr)] string outputFile,
[MarshalAs(UnmanagedType.LPWStr)] string templateFile,
[MarshalAs(UnmanagedType.LPWStr)] string userName,
[MarshalAs(UnmanagedType.LPWStr)] string manifestFilePath,
[MarshalAs(UnmanagedType.LPWStr)] string usersRightList);
[DllImport(#"*dll-path*")]
public static extern Int32 ProtectDocument(
[MarshalAs(UnmanagedType.LPStr)]string validToDate);
[DllImport(#"*dll-path*")]
public static extern void DebugGeneratedFiles(
[MarshalAs(UnmanagedType.LPWStr)] string singedIssuenceLicenseFilePath,
[MarshalAs(UnmanagedType.LPWStr)] string encryptedContentOutputFilePath);

Related

How to give a C# DLL a C-compliant interface?

A third-party app I have can call extension DLLs if they have C-compliant interfaces as described below.
I would like the third-party app to call my C# DLL, since I would rather write in C# than C. (Maybe my other choice would be to write a C DLL wrapper to call my C# DLL, which is an extra step that I might not get right).
I've searched the net and SO but haven't found (or recognized) a good match to my question.
The best suggestion seemed to be this special marshalling declarations in the C# code here: Calling a C# DLL from C; linking problems
Is it possible to write a C# DLL that has a C-compliant interface like the one below? If so, could someone tell me what I have to do or point me to some documentation?
The third-party app documentation says, "The DLL function must be a PASCAL function that takes a single LPCSTR (long pointer to a constant string) argument. C or C++ DLL functions called must have prototypes equivalent to:
extern "C" __declspec(dllexport) void __stdcall fn(LPCTSTR szParam );
Take a look at this article: https://www.codeproject.com/Articles/12512/Using-the-CDECL-calling-convention-in-C-changing
It discusses a different problem (opposite to yours) but also explains the linkage of C# functions - by default C# uses __stdcall (and it cannot be overridden). This means your third party app should be able to call the C# function as it stands. Have you tried it? Did you get any errors?

How to convert LPCTSTR to C# string using SWIG

I have to rebuild software that was written in C++/MFC & Unicode. There are two assemblies, one Server and one Client. The Client has to be rebuilt in C#+WPF.
Originally there was a .h file included by both assemblies, to share some global values. I want to use these values in the new C# assembly, too.
My first approach is to use SWIG. So I created a test-Project (that Outputs a DLL) that contains the .h file and let do SWIG its Magic.
This results in a C++ Wrapper for the C++ Project and some .cs files.
Then I created a C# WPF application, included the DLL and the generated cs files from swig.
So far so good.
The .h file contains basically int variables, classes that contain an enum each and some LPCTSTR strings (that are wchar_t * since I use Unicode).
const LPCTSTR ProductName = _T("XYZ");
const int MAX_MESS_ITEMS = 200;
class SPS
{
public:
enum SPS
{
SPS1 = 1,
SPS2 = 2,
SPS3 = 3,
};
};
Using the int and enums is no Problem, but swig isn't able to convert the LPCTSTR to C# string (without doing some customizing). Swig generates a SWIGTYPE_p_LPCTSTR type which does not allow me to get the original Content of the string as defined in the .h file.
As a next Approach I walked through the SWIG Documentation (I use version 3.0.12) and found out about typedef and typemaps.
I tried to include the windows.i and that gave me the first letter of the string assigned to a LPCTSTR variable.
Next I tried to figure out how to use a typemap for this, but I can't get this to work. For me it is pretty difficult to understand how to create a typemap (I have some Problems understanding what is done there and how the Syntax works). Also the lib (that I downloaded with the swigwin.zip) that contains some typemaps for std::string etc. does not help me.
Also Research on stackoverflow and MSDN did not take me closer to a solution.
Are there any good instructions or examples on how to crate a typemap for converting strings (especialy LPCTSTR) ?
What other easy-to-use tools can make the Job? Should I stop using SWIG and use _declspec(dllexport) stuff (with what I don't have any experience)?
I'm not in the Need to convert functions or highly-desgined classes. Just the strings, int, and enums.
Since the two assemblies are communicating over a namedpipe, I concerned to send some data over the pipe when starting the applications, but there are some Information from the global variables needed before the pipe starts doing its work.
Any help concerning this is appreciated :)

Generate C# wrapper from C include file

Suppose I have a dll written in pure C. I have an inculde file (.h) so I can use the dll from a VS 2012 C project.
Is there any way to generate a C# wrapper class based on the metainfo in the include file, or I must write all the [DllImport]... manually? The C source code for dll is also available.
(Please note: This is not a COM library)
Thanks in advance
There are tools that can help, but by and large you have to write the wrapper code yourself to some degree. The main reason being that a C header file does not fully specify the interface. For instance, consider this function:
void foo(int* x);
Does this function receive a pointer to a single int, or does it receive a pointer to an array? There's no way for you to tell with just this information. So, any tool that creates wrappers must also use some form of annotation to fully describe the semantics of the functions. If those annotations are not present you would need to create them. At which point it probably becomes quicker and easier to write the wrapper manually.
As an alternative to writing C# pinvokes you can use a mixed mode C++/CLI assembly. This can include the header file and link against the import library. Then all you need to do is write a C++/CLI ref class to wrap the interface, and add the C++/CLI assembly as a reference to your C# project.

Converting a C++ program into C#

I'm working on a project where I'm converting C++ code to C# manually. I have working knowledge of C# but I've never used C++ before.
What I need to know is how to deal with the header files, since C# does't have anything like that. Say I have buffer.h and buffer.cpp, would I just convert them both and include them in the same buffer.cs file?
Is the C++ header file in any way related to an Ada spec file?
The distinction between includes ".h files" and source ".cpp files" is only one of convention. The convention is that declaration (functions, classes, etc) are in .h files which are #included in implementation (definition), or .cpp files. For most cases you're fine in collapsing X.h and X.cpp to a single X.cs file.
That said, you still need to take a look at what is going on in each file. A basic understanding of C++ would go a long way here, and something I strongly recommend you acquire before you get too far into your translation.
It might help you to think of a C++ header file as containing two major types of things: the class definition, which defines its member data and "interface" (not to be confused with a C# interface type) and "other stuff". The class definition part contains method prototypes and class member variables.
The good news concerning the prototypes is that you simply don't need them in C#. Clients of your class receive prototype information from the implementation itself via the assembly for the namespace. The data members are contained within your C# class implementation, typically as private members which are exposed through C# properties.
The "other stuff" mentioned above can include #defines, which you typically want to turn into const definitions in C#. Other things such as enumerations have equivalents in C# which you of course move into the .cs file for your class.

Clarification for copying strings from native structures

I'm using the PInvoke stuff in order to make use of the SetupAPI functions from C++. I'm using this to get paths to USB devices conforming to the HID spec. I've got everything working but something I don't understand has me puzzled. Using this structure from the SetupAPI:
typedef struct _SP_DEVICE_INTERFACE_DETAIL_DATA {
DWORD cbSize;
TCHAR DevicePath[ANYSIZE_ARRAY];
} SP_DEVICE_INTERFACE_DETAIL_DATA, *PSP_DEVICE_INTERFACE_DETAIL_DATA;
I don't get the same results as the example code I'm using. First off, I'm using an IntPtr and allocating memory using Marshal.AllocHGlobal() to pass this back and forth. I call SetupDiGetDeviceInterfaceDetail() twice, first to get the size of the buffer I need, and second to actually get the data I'm interested in. I'm looking to get the Path to this device, which is stored in this struct.
The code I'm going off of does this:
IntPtr pDevPath = new IntPtr(pDevInfoDetail.ToInt32() + 4);
string path = Marshal.PtrToStringAuto(pDevPath);
Which works just fine. I did that and the string I got was gibberish. I had to change it to
IntPtr pDevPath = new IntPtr(pDevInfoDetail.ToInt32() + 4);
string path = Marshal.PtrToStringAnsi(pDevPath);
to make it work. Why is this? Am I missing some setting for the project/solution that informs this beast how to treat strings and chars? So far, the MSDN article for PtrToStringAuto() doesn't tell me much about it. In fact, it looks like this method should have made the appropriate decision, called either the Unicode or Ansi version for my needs, and all would be well.
Please explain.
First of all, +10000 on using a real P/Invoke interop type and not marshalling data by hand. But since you asked, here's what's going on with your strings.
The runtime decides how to treat strings and chars on a per-case basis, based on the attributes you apply to your interop declaractions, the context in which you use interop, the methods you call, etc. Every type of P/Invoke declaration (extern method, delegate, or structure) allows you to specify the default character size for the scope of that definision. There are three options:
Use CharSet.Ansi, which converts the managed Unicode strings to 8-bit characters
Use CharSet.Unicode, which passes the string data as 16-bit characters
Use CharSet.Auto, which decides at runtime, based on the host OS, which one to use.
In general, I hate CharSet.Auto because it's mostly pointless. Since the Framework doesn't even support Windows 95, the only time "Auto" doesn't mean "Unicode" is when running on Windows 98. But there's a bigger problem here, which is that the runtime's decision on how to marshal strings happens at the "wrong time".
The unmanaged code you are calling made that decision at compile time, since the compiler had to decide if TCHAR meant char or wchar -- that decision is based on the presence of the _UNICODE preprocessor macro. That means that, for most libraries, it's going to always use one or the other, and there's no point in letting the CLR "pick one".
For Windows system components, things are a bit better, because the Unicode-aware builds actually include two versions of most system function. The Setup API, for example, has two methods: SetupDiGetDeviceInterfaceDetailA and SetupDiGetDeviceInterfaceDetailW. The *A version uses 8-bit "ANSI" strings and the *W version uses 16-bit wide "Unicode" strings. It similarly has ANSI and Wide version of any structure which has a string.
This is the kind of situation where CharSet.Auto shines, assuming you use it properly. When you apply a DllImport to a function, you can specify the character set. If you specify Ansi for the character set, if the runtime doesn't find an exact match to your function name, it appends the A and tries again. (Oddly, if you specify Unicode, it will call the *W function first, and only try an exact match if that fails.)
Here's the catch: if you don't specify a character set on your DllImport, the default is CharSet.Ansi. This means you are going to get the ANSI version of the function, unless you specifically override the charset. That's most likely what is happening here: you are calling the ANSI version of SetupDiGetDeviceInterfaceDetail by default, and thus getting an ANSI string back, but PtrToStringAuto wants to use Unicode because you're probably running at least Windows XP.
The BEST option, assuming we can ignore Windows 98, would be to specify CharSet.Unicode all over the place, since SetupAPI supports it, but at the very least, you need to specify the same CharSet value everywhere.

Categories

Resources