How to marshal two dimensional TCHAR array? - c#

I have a DLL function in that converts a file to another format.
The function produces multiple files as output.
Therefore, it fills the 2nd parameter with the paths of the output files.
The C++ function is defined as the following:
int Convert(LPTSTR lpSource, TCHAR outputFileName[][MAX_PATH]);
How do I mashal the 2nd parameter so that my C# application can receive the output file paths correctly?
[DllImport("Convert.dll")]
private static extern int Convert(
[MarshalAs(UnmanagedType.LPTStr)] string lpszSource,
????
);
Thanks in advance.

I would make things simpler using C++/CLI (which is very good at building bridging layers between native C/C++ code and managed code).
Basically, you could write a thin C++/CLI layer that exposes a method that calls the native function in its body, and then copies the returned native strings into a gcnew-ly created array<String^>, and returns it to the C# managed caller.

I finally figured it out.
I changed my C++ function to the following:
int Convert(LPTSTR lpSource, LPTSTR *plpOutputFileName, int size);
And the C# declaration as:
[DllImport("Convert.dll")]
private static extern int Convert(
[MarshalAs(UnmanagedType.LPTStr)] string lpszSource,
[In, Out] String[] outputFileName,
int size
);
Thank you all for helping.

Related

Is it necessary to free the memory of strings in C++ received from C#?

I have the following exposed DLL functions in C++.
// center_of_rotation_api.h
// CENTER_OF_ROTATION_API is a macro like __cdecl(dllexport) on Windows
CENTER_OF_ROTATION_API void SerializeMesh(Mesh * mesh, const char * path);
CENTER_OF_ROTATION_API const char * SerializationError(Mesh * mesh);
From C#, I use the following.
// dll is the name of the compiled dll
[DllImport(dll)]
public static extern void SerializeMesh(IntPtr mesh, string path);
[DllImport(dll)]
public static extern IntPtr SerializationError(IntPtr mesh);
The IntPtr returned by SerializationError is allocated using new in C++. So I have another DLL exported function that frees the pointer when called by C#.
My question is, do I need to free the memory of the const char * path in the argument of SerializeMesh in C++?
No, the C# marshaler will take care of this for you. The char* will be valid during the lifetime of the PInvoke call. If your C++ code expects to own the char*, you should make a copy in SerializeMesh.
Here is a primer on string marshaling. If you really need to use a const char*, you might need to set the MarshalAsAttribute to UnmanagedType.LPStr. See here for more information on string marshaling behavior.
Here is another useful reference if you want to dig even deeper.

How to convert PInvoke `<[In](),Out()> ByRef` to C#?

I have a function from this VB.net that needs to be imported to C#.
I have tried various VB.NET to C# converters but it does not work correctly with the imported dll associated with this function.
Anyone knows how to convert correctly for the following VB function to C#:
<DllImport("E5KDAQ.dll")> _
Public Function E5K_ReadDIStatus(ByVal id As Short,<[In](),Out()> ByRef chnval As Integer) As Short
End Function
Using an online converter, it gives the following:
Convert c# which has error
[DllImport("E5KDAQ.dll")]
public static extern short E5K_ReadDIStatus(short id, [In()] out int chnval);
From official documentation here: http://www.acceed.de/manuals/inlog/EDAM5000_Manual.pdf there is a C++ definition, plus a bit of documentation on what the second parameter is, which is really what you want to look at:
VC++: (see E5KDAQ.h)
unsigned short E5K_ReadDIStatus (int id, unsigned long *Didata);
Parameters:
id: module ID address
Didata: points to a 32-bit buffer to store DI status
So the C# definition should simply be (long and int in C++ are 32-bit)
[DllImport("E5KDAQ")]
static extern ushort E5K_ReadDIStatus(int id, ref uint Didata)
You can use this.
public static extern short E5K_ReadDIStatus(short id, ref int[] chnval)
Reference: Are P/Invoke [In, Out] attributes optional for marshaling arrays?

typedef void* alternative in c#

I am using DLL runtime which is made with C language into C#.
I came across below statement.
typedef void *JCCP_PROPERTY_HANDLE;
In function it is being used as:
JCCP_RESULT __JCCP_FUNCTION__ jccpGetProperty(
JCCP_HANDLE hjccp,
const char *name,
JCCP_PROPERTY_HANDLE *phproperty);
Now I want to call jccpGetProperty() method in my C# code.
Can anybody tell how can I pass third parameter(JCCP_PROPERTY_HANDLE *phproperty) to function from C#.
I tried with below code but not working.
Extern Method:
[DllImport(DLL_NAME, EntryPoint = "_jccpGetProperty", CallingConvention = CallingConvention.Cdecl)]
public static extern IntPtr jccpGetProperty(IntPtr hjccp, string name, ref IntPtr JCCP_PROPERTY_HANDLE);
Usage
IntPtr handle = IntPtr.Zero;
string tag = "server.version";
var result = jccpGetProperty(hjccp, tag, ref handle);
Can anybody help me in this?
IntPtr is the correct type mapping for void*. The native type void* is generally used for an opaque pointer, and that is mapped to IntPtr in C#.
Those parts of the p/invoke declaration that we can verify are correct. The unverifible parts are:
The calling convention. You believe that it is cdecl, but we can't check.
The return type. You believe it to be pointer sized. Again we cannot check. My guess is that a 32 bit integer, int or uint is more likely. That would make a difference in a 64 bit process.
The values passed to the function. It's perfectly possible that the function is declared correctly, but you are passing invalid values.
Because you only showed partial code and details, it's hard to say much more. You will have to verify all the parts of the program that we cannot.
I suggest that you start with working C or C++ code and translate that, looking for the first point of deviation in behaviour between that code and your C# translation.

Call to external DLL from C# with integer pointer

I'm trying to call an external .dll function from c#. The doc for the dll defines the function:
int funcName(int *retVal)
I've tried various configurations and always the unbalanced stack error from p/invoke; My c# code currently looks like this:
[DLLImport("dllName");
unsafe static extern int funcName(ref IntPtr retVal);
unsafe IntPtr retNum;
int status = funcName(ref retNum);
Any ideas are appreciated!
Your p/invoke declaration has the wrong parameter type.
ref Int32 is the correct match for int*.
IntPtr can also work.
ref IntPtr would be int**. Definitely not what you want.
Use
[DLLImport("dllName")]
static extern int funcName(ref Int32 retVal);
Also make sure that the calling convention matches. You should never use a dllexport in C or C++ without also using an explicit calling convention, and then the C# DllImport needs to have the matching convention.
Generally the prototype in C++ should be
extern "C" int __stdcall funcName(int* arg);
Is there a header file provided for C and C++ clients that you could check to verify the signature?

PInvoke in 64bit .net app through c++ 64 bit dll

I'm having an issue calling a function in a c++ dll inside of a c# app. I'm calling the function inside of c# like so:
[DllImport("cryptopp.dll")]
public static extern IntPtr RSAEncryptString(string filename, string seed, string message);
It is being exported in the c++ dll as shown below.
extern "C" __declspec(dllexport) const char* __cdecl RSAEncryptString(const char *pubFilename, const char *seed, const char *message);
What I get when I try to call this, however, is an "An External component has thrown an exception." exception, which is not very descriptive at all, and extremely unhelpful.
When I pull up the dll in an export viewer, it shows all the other exported functions with fully quantified declarations (I.E. public: void __cdecl CryptoPP::X509PublicKey::`vbase destructor'(void) __ptr64 ) , except for the function I am calling, which just displays the function name RSAEncryptString.
This is the only possible issue I can see, besides maybe mis-calling the function with an invalid declaration on the c# side. Am I using System.Runtime.InteropServices.Marshal wrong?
Please help <3 and thanks in advance.
I think you need to change the first line to:
[DllImport("cryptopp.dll",
CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
If you want to get very descriptive, you can also add these:
public static extern IntPtr RSAEncryptString(
[In, MarshalAs(UnmanagedType.LPStr)] string filename,
[In, MarshalAs(UnmanagedType.LPStr)] string seed,
[In, MarshalAs(UnmanagedType.LPStr)] string message);
IIRC think the CharSet should take care of the encoding thing for you, but if it doesn't, use the MarshalAs also, as shown above.
Edit:
Oh I think I got why you still get an error! Your code still had the above problems, but it's still erring because you can't return a string object since it's not a managed object; you need to return a pointer (like IntPtr) and then use Marshal.PtrToStringAnsi!
(I didn't really look at your return type when answering this at first.)
It appears you're trying to store the return value of type const char * (an LPCSTR) into an IntPtr type (usually used for HANDLEs, not LPSTRs.) Try this:
[DllImport("cryptopp.dll", CharSet = CharSet.Auto)]
public static extern String RSAEncryptString(String filename, String seed, String message);
Also keep in mind that if any argument is getting written to, you'll need to add out before its type, i.e. ..., out String message)

Categories

Resources