---
title: "一些代码片段"
author: "larrytang"
date: "2010-11-29T21:40:13Z"
tags: ["C", "C#", "C++", "Lua", "算法"]
categories: ["编程语言"]
slug: "untitled"
draft: false
lastmod: "2010-11-29T21:40:13Z"
id: 828650
url: "https://larrytang.iteye.com/blog/828650"
---

1.不要用return语句返回指向“栈内存”指针。

```C++

char* getmem(int num)
{
    char *p = (char*)malloc(sizeof(char)*num);
    return p;
}

int main(int argc, char* argv[])
{
    char *str = NULL;
    str = getmem(12);
    strcpy(str, "Hello fuck!");
    cout<<str<<endl;
    free(str);
    return 0;
}

```

这种方式是可以的，因为返回的不是“栈内存”指针。所谓的“栈内存”指针是指固定大小的数组、
变量等。

2.一个不错的字符串 hash 函数

```C++

unsigned long hash(const char *name,size_t len)
{
    unsigned long h=(unsigned long)len;
    size_t step = (len>>5)+1;
    for (size_t i=len; i>=step; i-=step)
        h = h ^ ((h<<5)+(h>>2)+(unsigned long)name[i-1]);
    return h;
}

```

一个方便的 hash 函数应该散列的比较开，计算速度跟字符串长度关系不大，又不能只计算字符
串的开头或末尾。这里的算法是从Lua 中看来的。

3.UTF8 到 UTF16 的转换(单个字符)

```C++

int UTF8toUTF16(int c)
{
    signed char *t=(signed char*)&c;
    int ret=*t &(0x0f | (~(*t>>1) &0x1f) | ~(*t>>7));
    int i;
    assert ((*t & 0xc0) != 0x80);
    for (i=1;i<3;i++) {
        if ((t[i] & 0xc0)!=0x80) {
            break;
        }
        ret=ret<<6 | (t[i] & 0x3f);
    }
    return ret;
}

```

这只是一个字符的转换，如果转换字符串，可以再做一点优化。

4.宽字符和窄字符转换的问题

```C++

BOOL UnicodeToAnsi(LPWSTR pszwUniString, LPSTR pszAnsiBuff, DWORD dwAnsiBuffSize)
{
    int iRet = 0;
    iRet = WideCharToMultiByte(CP_ACP, 0, pszwUniString, -1, pszAnsiBuff,
    dwAnsiBuffSize, NULL, NULL);
    return (0 != iRet);
}

BOOL AnsiToUnicode(LPSTR pszAnsiString, LPWSTR pszwUniBuff, DWORD dwUniBuffSize)
{
    int iRet = 0;
    iRet = MultiByteToWideChar(CP_ACP, 0, pszAnsiString, -1, pszwUniBuff,
    dwUniBuffSize);
    return (0 != iRet);
}

```


// 应用示例

```C++

LPSTR lpCmdLine;
LPWSTR lpwCmdLine;
AnsiToUnicode(lpCmdLine, lpwCmdLine, sizeof(lpwCmdLine));
lpCmdLine = NULL;
UnicodeToAnsi(lpwCmdLine, lpCmdLine, sizeof(lpwCmdLine));
static_cast<char*>(lpCmdLine);
// Function that safely converts a 'WCHAR' String to 'LPSTR':
char* ConvertLPWSTRToLPSTR (LPWSTR lpwszStrIn)
{
    LPSTR pszOut = NULL;
    if (lpwszStrIn != NULL)
    {
        int nInputStrLen = wcslen (lpwszStrIn);
        // Double NULL Termination
        int nOutputStrLen = WideCharToMultiByte (CP_ACP, 0, lpwszStrIn, nInputStrLen, NULL, 0, 0, 0) + 2;
        pszOut = new char [noutputstrlen];
        if (pszOut)
        {
            memset (pszOut, 0x00, nOutputStrLen);
            WideCharToMultiByte(CP_ACP, 0, lpwszStrIn, nInputStrLen, pszOut,
            nOutputStrLen, 0, 0);
        }
    }
    return pszOut;
}

```