【发布时间】:2011-11-16 01:37:39
【问题描述】:
我需要创建一个 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(/* */ 中的部分)中做比现在做的更多的事情,但我被前两个问题阻止了......
感谢大家的帮助
【问题讨论】: