私はC#用のC++ライブラリをビルドしています。しかし、memsetやmemcpyがあると私のプログラムは亡くなりました。C#はmemsetでmemsetでC++ dllを実行できません
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.InteropServices;
namespace CsharpCallDll
{
public class dllfunction
{
[DllImport("dllgen.dll", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public static extern int calData(ref double data, int data_size,
ref double info, int info_size, ref char result,int max_result_size,ref int realResultSize);
}
class Program
{
static void Main(string[] args)
{
int data_size = 2;
double[] data = new double[data_size];
int info_size = 3;
double[] info = new double[info_size];
int max_result_size = 1000;
char[] result = new char[max_result_size];
int real_result_size = 0;
data[0] = 1;
data[1] = 2;
info[0] = 1;
info[1] = 2;
info[2] = 3;
unsafe
{
dllfunction.calData(ref data[0], data_size,
ref info[0], info_size, ref result[0], max_result_size,ref real_result_size);
Console.Write(result + "\n");
}
Pause();
}
public static void Pause()
{
Console.Write("Press any key to continue . . . ");
Console.ReadKey(true);
}
}
}
C++
MG_API int calData(double *data, int dataSize,
double *info, int infoSize, char* result, int maxresultSize, int* realResultSize)
{
int errorCode = 0;
if (dataSize == 0 || infoSize == 0)
{
errorCode = 1;
}
string resultArray = "";
double* tempvalue = new double;
string isnormal;
string abnromaltype;
int resultSiz = 0;
for (int i = 0; i < 15; i++)
{
srand((int)time(NULL)+i);
*tempvalue = (double)Random(10);
if (*tempvalue > 8) {
isnormal = "false";
abnromaltype = abnromalTypeS[0];
}else if (*tempvalue < 2) {
isnormal = "false";
abnromaltype = abnromalTypeS[1];
}else{
isnormal = "true";
abnromaltype = abnromalTypeS[2];
}
resultArray = appendResultIntoString(resultArray, dataNameS[i], *tempvalue,
dataUnitS[i], isnormal, abnromaltype);
}
*realResultSize = resultArray.size();
// print the result
cout << "this is the resultsize ";
cout << *realResultSize << endl;
// result = (char*) malloc(*resultSize);
memset(result, 0, maxresultSize);
// memcpy(result, resultArray.c_str(), *realResultSize);
delete tempvalue;
return errorCode;
}
resultArrayが文字列結果である
C番号:以下のコードです。
私のqeustionは: です。1. memcpy、memsetがC++コードにある場合、C#プログラムはそこで死んでしまいます。何が起こった?ところで
: 2. C++からC# 3に動的な長さの文字列を送信する方法があり、C++からC#
に[]文字列を送信する方法があります皆さんありがとうございました!
c#の文字は2バイトで、C++の文字列は1バイトの配列です。したがって、文字列配列をbyte []として渡す必要があります。 C++の配列はポイントなので、IntPtrとして渡す必要があります。 – jdweng
なぜあなたはC++/CLIを試してみませんか –