Reputation: 41
I am working on a C# project that will use a .dll (written in C) When passing a char array to the .dll function runInterpretation I am getting extra characters added to my string.
C# code:
[DllImport(@"c:\projectName\main.dll", CallingConvention = CallingConvention.Cdecl, EntryPoint = "runInterpretation")]
public static extern int runInterpretation(char[] inputStr);
static void Main(string[] args)
{
string inputString = "DR1234,2014/07/27 15:20:10,1,0,3,0,0,2,5,30,10,10,0,55,205,21500,86400,110,0,";
int tmp = runInterpretation(inputString.ToCharArray());
}
Which calls a C .dll:
#include <stdio.h>
#include <time.h>
#include <string.h>
#include "fixedtext.h"
#include "englarrini.h"
#include "numarrini.h"
#include "argcvalue.c"
#include "dgavalid.c"
#include "ratio.c"
#include "interp.c"
#include "validdisplay.c"
#ifdef DEVX
#define DATAFILEPATH "/home/drmcc/log/"
#elif DEVY
#define DATAFILEPATH "/home/drmcc/log/"
#elif PC
#define DATAFILEPATH ".\\data\\"
#else
#define DATAFILEPATH ".\\data\\"
#endif
__declspec(dllexport) int runInterpretation(char *inputString[])
{
printf("args %s\n", inputString);
return 1;
}
The end result when running my C# project is as follows (random extra chars after the last ',')
I would like to know why the extra characters are being added and how might I get rid of them.
Thank you
Upvotes: 0
Views: 708
Reputation: 1536
I don't think you want what you have for your C dll's argument. If you're just wanting one string passed in, then it should be:
__declspec(dllexport) int runInterpretation(char *inputString)
or better:
__declspec(dllexport) int runInterpretation(wchar_t *inputString)
From there, you just need to tell C# how to marshal your string. The easiest way to do that is to use the MarshalAsAttribute. If you go with the char * interpretation, use
public static extern int runInterpretation(
[MarshalAs(UnmanagedType.LPStr)]
String inputStr);
or the Unicode version:
public static extern int runInterpretation(
[MarshalAs(UnmanagedType.LPWStr)]
String inputStr);
It's also worth noting that if you change your C parameter to Unicode, you don't have to use the Marshalling hint at all in C# as it will marshal correctly by default.
Upvotes: 4
Reputation: 30418
In C, strings are expected to be null terminated. The "extra characters" are whatever happens to be in memory after the array until a null character is found. ToCharArray()
won't append a null character because that wouldn't make sense in the context of C#. I can think of two ways to fix this:
ToCharArray()
. See https://stackoverflow.com/a/2794356/3857 for an exampleUpvotes: 1