gpt4 book ai didi

c# - 在 C# 中调用更改传递参数的 c dll 函数

转载 作者:太空宇宙 更新时间:2023-11-03 23:29:14 25 4
gpt4 key购买 nike

我正在尝试将 C# 字符串传递给应该加密它的 C dll 函数。不幸的是,它什么都不做。调用函数后,字符串还是一样。

C 函数:

    #include <stdio.h>
#include <stdlib.h>
extern "C"{
__declspec(dllexport) void Encrypt( char *plainText,long height,long inputLength)
{
unsigned char *encryptedText=(unsigned char*)malloc(sizeof(plainText));
unsigned char **cipherArray;


cipherArray=(unsigned char**)malloc(height*sizeof(unsigned char *));
for(long i=0; i<height; i++)
{
cipherArray[i]=(unsigned char*)malloc(inputLength*sizeof(char));
for (long j=0; j<inputLength ; j++)
cipherArray[i][j]='#';
}






bool addRow=true;
long row=0;
long column = 0;
long arrayIterator = 0;
while(arrayIterator<inputLength){
cipherArray[row][column] = plainText[arrayIterator];

column++;
if(addRow)row++;
else row--;
if (row >= height)
{
row--;
row--;
addRow=false;
}
else if (row < 0)
{
row++;
row++;
addRow = true;
}
arrayIterator++;
}



long iterator=0;
for (long i=0; i< height; i++)
for(long j=0; j<inputLength;j++){
if(cipherArray[i][j]!='#'){
encryptedText[iterator]=cipherArray[i][j];
iterator++;
}
}

long j=0;
while(j<inputLength){
plainText[j]=encryptedText[j];
printf("%c",encryptedText[j]);
j++;
}

for(long i=0; i<height; i++)
free(cipherArray[i]);
free(cipherArray);
cipherArray = NULL;


}

}

包含 C# 类:

    namespace RailFenceCipher
{
public class CCipher
{
[DllImport("Win32Project3.dll", EntryPoint = "Encrypt", CallingConvention = CallingConvention.Cdecl, CharSet = CharSet.Ansi)]
public static extern void Encrypt([MarshalAs(UnmanagedType.LPStr)] string plainText, long height, long inputLength);



}
}

并调用函数:

     private void cipherC()
{

string plainText = this.fileInput;
Console.WriteLine("=== C# test, using IntPtr and Marshal ===");
CCipher.dllprint();
CCipher.Encrypt(plainText, this.height, this.fileInput.Length);
this.fileOutputC = plainText;
Console.WriteLine("=== END ===");
}

调用后plainText没有变化。

最佳答案

这是意料之中的。您正在编码数据,但没有编码数据。这是字符串类型参数的行为。您需要使用 StringBuilder 才能从 native 代码编码文本。

另外,C# long 是 64 位的,而 C++ long 是 32 位的。你的 pinvoke 应该是:

[DllImport("Win32Project3.dll", CallingConvention = CallingConvention.Cdecl, 
CharSet = CharSet.Ansi)]
public static extern void Encrypt(StringBuilder plainText,
int height, int inputLength);

并且您需要确保您传递的 StringBuilder 实例的容量足以返回文本。

也许更大的问题是您的 C++ 代码已损坏。至少,您需要修复接收 sizeof(plainText) 的 malloc 调用。那是指针的大小。您需要传递缓冲区的长度,inputLength。在尝试互操作之前,您应该先调试该代码。

关于c# - 在 C# 中调用更改传递参数的 c dll 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19644833/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com