我写的dll需要返回一个字符串,而且由于需要被别的语言调用,所以我用LPTSTR作为输出参数,在函数内部,我是用CString来操作字符串,但不知如何转换?
另外,我用的全是TCHAR类型,strcpy(),strcat()这些函数用不了,如果我不用CString,我该怎样来操作字符串啊?
另外,我用的全是TCHAR类型,strcpy(),strcat()这些函数用不了,如果我不用CString,我该怎样来操作字符串啊?
TCHAR型? 是typedef char TCHAR;, 还是unicode(WCHAR)?
用memcpy代替看行不行.
用CString的成员函数解决不了?
LPTSTR pp;
pp = strFile.GetBuffer(0);//这样没问题TCHAR类型,strcpy(),strcat()这些函数用不了?
==>
1 可以用_tcscpy(),_tcscat() //include "TCHAR.H"
2 如果没有定义_UNICODE编译开关,TCHAR等同于char
LPTSTR SomeFunc();//估计你原来的函数原型是这样的,这种方式存在很多问题
BOOL SomeFunc(LPTSTR pszBuf, int nBufLen);//现在这样定义
CString m_ss;
m_str = m_ss.GetBuffer(0);
其中,GetBuffer(0)是得到字符的堆地址的,0是说在第一个为之开始
extern "C" int WINAPI MD5Normal(PCHAR InputText,int InputTextLen,LPTSTR OutputText)//LPTSTR OutputText为输出参数
{
try
{
MD5 md5;
CString CString1,CString2;
unsigned char OutputText2[17];
memset(OutputText2,0,17);
md5.Encrypt(InputText,InputTextLen,OutputText2);
int i;
for (i=15;i>=0;i--)
{
CString1.Format("%x",OutputText2[i]);
CString2.Insert(0,(LPCTSTR)CString1);
}
CString2.MakeUpper();
MessageBox(NULL,CString2,"aaa",MB_OK);//调试表明前面的结果是正确的
//OutputText=(LPTSTR)(LPCTSTR)CString2;
OutputText=CString2.GetBuffer(0);
return strlen(OutputText);
}
catch(CException e1)
{
return 0;
}
}
上面是在vc中的代码(dll),用def文件输出
下面是在vb中的引用:
Private Declare Function MD5Normal Lib "md5.dll" (ByVal i1 As String, ByVal len1 As Long, o1 As String) As Long
Private Sub Command1_Click()
Dim out1 As String
Dim r1 As Long
r1 = MD5Normal("a", 1, out1)
MsgBox r1 //得到的字符串长度是正确的
Text2.Text = Left(out1, r1)//这个结果不对,总是空的,为什么啊?
End Sub
CString2是栈里变量,能行么?
static CString CString2; 试一下.或者VB这边准备好足够空间的buffer,传指针过去,(象你已经作的).lstrcpy(OutputText, CString2);
所以我建议你用“BSTR”作为输出
static CString CString2; 试一下.//还是不行,结果跟原来一样lstrcpy(OutputText, CString2); //vb程序发生内存不能读其中vb程序
Dim out1 As String
改为
Dim out1 As String *255 '长度肯定足够
看看,对你有用
memset( buf, 0, max );
strcat( buf, ( LPCTSTR )string );
return ( LPTSTR )buf;
所以转化为 CString可直接用等号, 如***=....或format;
另外转化为LPTSTR ,只需强制转换