gpt4 book ai didi

c++ - 通过对 dll 的 stdcall 操作字符串时出现问题

转载 作者:行者123 更新时间:2023-11-28 08:14:15 25 4
gpt4 key购买 nike

我需要创建一个 C++ dll,它将通过 stdcall 从另一个程序调用。

需要什么:调用程序将字符串数组传递给 dll,dll 应该更改数组中的字符串值。然后,调用程序将继续使用来自 dll 的这些字符串值。

我做了一个简单的测试项目,我显然遗漏了一些东西......

这是我的测试 C++ dll:

#ifndef _DLL_H_
#define _DLL_H_

#include <string>
#include <iostream>

struct strStruct
{
int len;
char* string;
};

__declspec (dllexport) int __stdcall TestFunction(strStruct* s)
{
std::cout << "Just got in dll" << std::endl;

std::cout << s[0].string << std::endl;
//////std::cout << s[1].string << std::endl;

/*
char str1[] = "foo";
strcpy(s[0].string, str1);
s[0].len = 3;

char str2[] = "foobar";
strcpy(s[1].string, str2);
s[1].len = 6;
*/

//std::cout << s[0].string << std::endl;
//std::cout << s[1].string << std::endl;

std::cout << "Getting out of dll" << std::endl;

return 1;
}

#endif

这是一个简单的 C# 程序,我用它来测试我的测试 dll:

 using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;

namespace TestStr
{
class Program
{
[DllImport("TestStrLib.dll", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.StdCall)]
public static extern int TestFunction(string[] s);

static void Main(string[] args)
{
string[] test = new string[2] { "a1a1a1a1a1", "b2b2b2b2b2" };

Console.WriteLine(test[0]);
Console.WriteLine(test[1]);

TestFunction(test);

Console.WriteLine(test[0]);
Console.WriteLine(test[1]);

Console.ReadLine();
}
}
}

这是产生的输出:

a1a1a1a1a1
b2b2b2b2b2
Just got in dll
b2b2b2b2b2
Getting out of dll
a1a1a1a1a1
b2b2b2b2b2

我有一些问题:

1) 为什么它输出的是数组第二个位置的元素而不是第一个位置?

2) 如果我取消注释 dll 文件中用//////注释的行,程序会崩溃。为什么?

3) 显然我想在 dll(/* */中的部分)中做比现在做的更多的事情,但我被前两个问题阻止了...

谢谢你的帮助

最佳答案

您不能将 string[] 编码为原生 struct

    [DllImport("TestStrLib.dll", CharSet = CharSet.Ansi, 
CallingConvention = CallingConvention.StdCall)]
public static extern int TestFunction(string[] s);

struct strStruct
{
int len;
char* string;
}

__declspec (dllexport) int __stdcall TestFunction(strStruct* s);

请阅读http://msdn.microsoft.com/en-us/library/fzhhdwae.aspx用于各种类型的编码。

在 C# 中

    [DllImport( "TestStrLib.dll" )]
public static extern int TestFunction([In, Out] string[] stringArray
, int size);

在 C++ 中

__declspec(dllexport) int TestFunction( char* ppStrArray[], int size)
{
return 0;
}

关于c++ - 通过对 dll 的 stdcall 操作字符串时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8145586/

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