<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>浏忙大爆炸 &#187; C++</title>
	<atom:link href="http://blog.waterlin.org/articles/tag/c/feed" rel="self" type="application/rss+xml" />
	<link>http://blog.waterlin.org</link>
	<description>源于理工科男的烂笔头情结</description>
	<lastBuildDate>Fri, 03 Feb 2012 08:35:37 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.1.3</generator>
		<item>
		<title>C# 引用 C++ 链接库</title>
		<link>http://blog.waterlin.org/articles/link-cpp-dll-from-csharp.html</link>
		<comments>http://blog.waterlin.org/articles/link-cpp-dll-from-csharp.html#comments</comments>
		<pubDate>Fri, 03 Feb 2012 08:35:37 +0000</pubDate>
		<dc:creator>waterlin</dc:creator>
				<category><![CDATA[技术]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[Windows]]></category>

		<guid isPermaLink="false">http://blog.waterlin.org/articles/link-cpp-dll-from-csharp.html</guid>
		<description><![CDATA[最近在尝试用新的方式来写一个新的 Windows 客户端，当作练习。主要是用 C++ 把复杂的算法写成链接库，然后用 C# 做界面前端，从 C# 调用用 C++ 写好的非托管代码。 尝试通过这种方式解决两个问题： C# 的计算效率问题，虽然从各种资料来看，好像 C# 的托管代码对效率的影响并没有想象的夸张，但不管怎么样，有些东西用 C++ 写就是方便一些； 用 C++ 可以方便地链接现有的代码库、算法库。 其实，这种架构可以看成是一种 C/S 架构的简化版，但是省去了 Socket 通信这一层。 我采用的是最简单的 P/Invokes 的方式来实现 C# 调用 C++ 链接库，详细的教程，可以看一下 Using dumpbin.exe as an Aid for Declaring P/Invokes 这篇文章。 这里先简单说说两点和代码无关的问题 如果 C++ 链接库的计算很耗时，一定要在 C# 客户端里开一个线程来处理，否则容易造成死机，这和 MFC 之类的原理一样。 为了测试你从 C# 链接 C++ 链接库是否成功，可以用 [...]]]></description>
			<content:encoded><![CDATA[<p>最近在尝试用新的方式来写一个新的 Windows 客户端，当作练习。主要是<a href="http://cn.waterlin.org/Microsoft/visual-studio-dll-project.html">用 C++ 把复杂的算法写成链接库</a>，然后用 C# 做界面前端，从 C# 调用用 C++ 写好的非托管代码。</p>
<p>尝试通过这种方式解决两个问题：</p>
<ol>
<li>C# 的计算效率问题，虽然从各种资料来看，好像 C# 的托管代码对效率的影响并没有想象的夸张，但不管怎么样，有些东西用 C++ 写就是方便一些；</li>
<li>用 C++ 可以方便地链接现有的代码库、算法库。</li>
</ol>
<p>其实，这种架构可以看成是一种 C/S 架构的简化版，但是省去了 Socket 通信这一层。</p>
<p>我采用的是最简单的 P/Invokes 的方式来实现 C# 调用 C++ 链接库，详细的教程，可以看一下 <a href="http://msdn.microsoft.com/en-us/library/aa446532.aspx">Using dumpbin.exe as an Aid for Declaring P/Invokes</a> 这篇文章。</p>
<div class="outline-3">
<h3 id="sec-1.1">这里先简单说说两点和代码无关的问题</h3>
<div class="outline-text-3">
<ol>
<li>如果 C++ 链接库的计算很耗时，一定要在 C# 客户端里开一个线程来处理，否则容易造成死机，这和 MFC 之类的原理一样。</li>
<li>为了测试你从 C# 链接 C++ 链接库是否成功，可以用 C# 新建一个命令行工程专门测试，用这种方式来测试更加直接与有效。</li>
</ol></div>
</p></div>
<div class="outline-3">
<h3 id="sec-1.2">再谈几点有关技术实现细节的问题，也是我折腾了很久的困惑之处</h3>
<div class="outline-text-3">
<div class="outline-4">
<h4 id="sec-1.2.1">1. 有关 C++ 链接库 EntryPoint 的名称</h4>
<div class="outline-text-4">
<p>我在刚开始从 C# 里链接 C++ 链接库的 API 时，想当然地以为就是函数名称。但是这样操作无论如何也调用不成功，<a href="http://msdn.microsoft.com/en-us/library/aa288468(v=vs.71).aspx#pinvoke_callingdllexport">需要在 C++ 链接库里添加一个 extern 关键字</a>，否则链接库编译出来的 API 名称，是混淆过的，不方便你在 C# 里作为 EntryPoint 来书写。</p>
<p>比如说，有如下 C++ 链接库的 API 函数（建议链接库给外面调用的 API 最好用 C 风格来实现，方便减少头文件依赖关系）：</p>
<pre>
<span>extern</span> <span>"C"</span> <span>__declspec</span>(dllexport) <span>bool</span> <span>Function1</span>(<span>const</span> <span>char</span>* <span>param1</span>,
                                                <span>const</span> <span>char</span>* <span>param2</span>,
                                                <span>const</span> <span>char</span>* <span>param3</span>);
</pre>
<p>翻译成 C# 函数则如下：</p>
<pre>
[DllImport(<span>"Example.dll"</span>, EntryPoint = <span>"Function1"</span>, ExactSpelling = <span>false</span>]
[<span>return</span>: MarshalAs(UnmanagedType.U1)]
<span>public</span> <span>static</span> <span>extern</span> <span>bool</span> Function1([MarshalAs(UnmanagedType.LPStr)] String param1,
                                    [MarshalAs(UnmanagedType.LPStr)] String param2,
                                    [MarshalAs(UnmanagedType.LPStr)] String param3);
</pre>
<p>这里注意，找 EntryPoint 一定要准确，否则不容易找到。为了明确地找到 API 函数的 EntryPoint 名称，可以使用 Dumpbin.exe 工具。</p>
<p>dumpbin.exe 工具默认在以下目录：</p>
<pre>
C:\Program Files\Microsoft Visual Studio 9.0\VC\bin
</pre>
<p>如果从这个目录里运行 dumpbin.exe 会提示找不到动态链接库 mspdb80.dll 的错误，可以把 dumpbin.exe 拷贝到目录</p>
<pre>
C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE
</pre>
<p>，并从这个目录下运行 dumpbin.exe 来解决这个问题。</p>
<p>运行命令</p>
<pre>
dumpbin.exe /EXPORTS dllname.dll
</pre>
<p>后，你会看到很多 ? @ 混合在一起的名称，所以，为了使你在 C# 里的代码可读性比较强，需要改造这些名称。在链接库里，我们可以通过用 extern 关键字来标明，这样生成的链接库 EntryPoint 依然会是原始的名称。</p>
</p></div>
</p></div>
<div class="outline-4">
<h4 id="sec-1.2.2">2. C# 程序运行时提示说找不到链接库</h4>
<div class="outline-text-4">
<p>如果按上述方法编写好了代码，一运行 C# 程序却提示说：</p>
<pre>
未处理的"System.DllNotFoundException"类型的异常出现在 example.exe 中。

其他信息: 无法加载 DLL"cppexample.dll": 找不到指定的模块。 (异常来自 HRESULT:0x8007007E)。
</pre>
<p>这个时候，你需要找一找你的 dll 是否在可执行目录下，或是你写的 dll 是否依赖于其它第三方dll，一定要确保所有的 dll 都能顺利被找到。</p>
</p></div>
</p></div>
<div class="outline-4">
<h4 id="sec-1.2.3">3. 参数的映射办法</h4>
<div class="outline-text-4">
<p>你的函数肯定有若干个参数，那这些参数应该和 C# 里的类型如何一一对应呢？在 C# 里，<a href="http://msdn.microsoft.com/en-us/library/aa288468(v=vs.71).aspx#pinvoke_defaultmarshaling">这种映射关系叫做 marshal</a>。</p>
<p>类型映射，需要仔细检查一下手册，比如说，const char* 就应该这样映射：</p>
<pre>
[MarshalAs(UnmanagedType.LPStr)]
</pre>
<p><a href="http://msdn.microsoft.com/en-us/library/2x8kf7zx(v=vs.80).aspx">Using C++ Interop</a> 文章的未尾，有列出一大串的类型映射列表。</p>
</p></div>
</p></div>
</p></div>
<div class="outline-3">
<h3 id="sec-1.3">小结</h3>
<div class="outline-text-3">
<p>初步用 C# 来写界面，感觉更方便、快速，起码比 MFC 来得简单、直接；从 C# 里直接调用 C++ 链接库，也很方便。但这两者结合起来写应用，稳定性还有待进一步测试。</p>
</p></div>
</p></div>
</p></div>
]]></content:encoded>
			<wfw:commentRss>http://blog.waterlin.org/articles/link-cpp-dll-from-csharp.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>C/C++ 多线程参数需要尽量采用动态分配的方式来分配</title>
		<link>http://blog.waterlin.org/articles/cpp-multi-thread-passing-params-problems.html</link>
		<comments>http://blog.waterlin.org/articles/cpp-multi-thread-passing-params-problems.html#comments</comments>
		<pubDate>Thu, 02 Feb 2012 06:40:00 +0000</pubDate>
		<dc:creator>waterlin</dc:creator>
				<category><![CDATA[技术]]></category>
		<category><![CDATA[C++]]></category>

		<guid isPermaLink="false">http://blog.waterlin.org/articles/cpp-multi-thread-passing-params-problems.html</guid>
		<description><![CDATA[在 C/C++ 多线程编程下，如果不注意，采用普通变量传递参数值给线程会有一些误区，需要特别小心。 下面浏忙绪绪就举两个例子来说明一下。 char* 参数在多线程下出现的怪异现象 最近在用 Boost 库写多线程程序时，需要启动若干个线程，这些线程分别处理不同的事情，线程会获取一个字符串参数，用来标识内容。在编写代码的时候，出现了一个很怪异的现象，例子代码如下： const int tNum = 4;//并发线程数 vector&#60;boost::thread*&#62; tBox; for (int i=0; i &#60; tNum; i++ ) { char strThread[20]; sprintf(strThread, "thread%d",i); //strThread 字符串是传入的 const char* 类型 boost::thread* thread_0 = new boost::thread( StreamProcesser, param1, param2, strThread); tBox.push_back(thread_0); boost::xtime xt; boost::xtime_get(&#38;xt, boost::TIME_UTC); xt.sec += 2; boost::thread::sleep(xt); } for (int [...]]]></description>
			<content:encoded><![CDATA[<p>在 C/C++ 多线程编程下，如果不注意，采用普通变量传递参数值给线程会有一些误区，需要特别小心。</p>
<p>下面<a href="http://blog.waterlin.org">浏忙绪绪</a>就举两个例子来说明一下。</p>
<div class="outline-3">
<h3 id="sec-1.1">char* 参数在多线程下出现的怪异现象</h3>
<div class="outline-text-3">
<p>最近在用 <a href="http://blog.waterlin.org/articles/compile-and-install-boost-under-cygwin.html">Boost 库</a>写多线程程序时，需要启动若干个线程，这些线程分别处理不同的事情，线程会获取一个字符串参数，用来标识内容。在编写代码的时候，出现了一个很怪异的现象，例子代码如下：</p>
<pre>
<span>const</span> <span>int</span> <span>tNum</span> = 4;<span>//</span><span>并发线程数
</span><span>vector</span>&lt;<span>boost</span>::<span>thread</span>*&gt; <span>tBox</span>;

<span>for</span> (<span>int</span> <span>i</span>=0; i &lt; tNum; i++ )
{
    <span>char</span> <span>strThread</span>[20];
    sprintf(strThread, <span>"thread%d"</span>,i);
    <span>//</span><span>strThread 字符串是传入的 const char* 类型
</span>    <span>boost</span>::<span>thread</span>* <span>thread_0</span> = <span>new</span> <span>boost</span>::<span>thread</span>( StreamProcesser,
                                                 param1,
                                                 param2,
                                                 strThread);

    tBox.push_back(thread_0);

    <span>boost</span>::<span>xtime</span> <span>xt</span>;
    <span>boost</span>::xtime_get(&amp;xt, <span>boost</span>::TIME_UTC);
    xt.sec += 2;
    <span>boost</span>::<span>thread</span>::sleep(xt);
}

<span>for</span> (<span>int</span> <span>i</span>=0; i &lt; tNum; i++ )
{
    <span>boost</span>::<span>thread</span>* <span>thread_0</span> = tBox[i];
    thread_0-&gt;join();
    <span>delete</span> thread_0;
}
</pre>
<p>在线程函数启动参数中，有一个参数是 const char* 类型。如果我在线程中，没有先对 char 字符串拷贝一个副本，则当4个线程都跑起来后，再去读取这个参数，很有可能会读到同一个字符串。</p>
<p>这是因为编译器把 strThread 的地址编码为同一个内存地址造成的，所以，所有的线程读取的都是最后一次设置 strThread 的值。</p>
<p>结论：</p>
<ol>
<li>传入 char* 后，一定要对 char 字符串拷贝一个副本，否则这个指针指向的内容很有可能被改变；</li>
<li>多用 C++ 的 string，少用 char 或是 char*，用值拷贝的方式比单纯传递一个指针要更安全；</li>
<li>最安全的做法，应该是动态分配一个空间，用来保存传递给线程的参数值，在线程结束后再销毁该值。</li>
</ol></div>
</p></div>
<div class="outline-3">
<h3 id="sec-1.2">int 参数在多线程下被重复赋值的怪异现象</h3>
<div class="outline-text-3">
<p>同样，如果传入参数是整型或是其它类型的时候，也会有上述类似的问题。<a href="http://cn.waterlin.org/Microsoft/Visual-studio-unusual.html">拿 Win32 的 CreateThread 函数</a>来说，同样需要保证传入的参数不被修改，例如下面的代码就非常危险：</p>
<pre>
DWORD <span>WINAPI</span> <span>CloseThreadFun</span>( <span>LPVOID</span> <span>param</span>)
{
    <span>int</span>* <span>pHandle</span> = (<span>int</span>*)param;
    <span>const</span> <span>int</span> <span>handle</span> = *pHandle;

    <span>//</span><span>打印句柄
</span>    printf(<span>"get handle is %d"</span>, handle);

    <span>return</span> 0;
}

<span>int</span> <span>_tmain</span>(<span>int</span> <span>argc</span>, <span>_TCHAR</span>* <span>argv</span>[])
{
    <span>const</span> <span>int</span> <span>THREAD_NUM</span> = 4;

    <span>HANDLE</span>* <span>lphandle</span> = <span>new</span> <span>HANDLE</span>[THREAD_NUM];
    <span>for</span> (<span>int</span> <span>j</span> = 0; j &lt; THREAD_NUM; j++)
    {
        <span>HANDLE</span> <span>hthread</span>;
        hthread = CreateThread(<span>NULL</span>, 0, CloseThreadFun, (<span>LPVOID</span>)&amp;j, 0, <span>NULL</span>);
        lphandle[j] = hthread;
    }

    WaitForMultipleObjects(THREAD_NUM, lphandle, TRUE, INFINITE);

    <span>delete</span> [] lphandle;

    <span>return</span> 0;
}
</pre>
<p>在调用 CloseThreadFun 来启动一个线程后，j 的值很有可能已经被修改掉了：线程启动总是需要时间的，而参数指针指向地址的内容，很有可能在此期间被修改了。比如，上面的代码，运行后，打印的内容如下：</p>
<pre>
get handle is 3
get handle is 4
get handle is 4
get handle is 4
</pre>
<p>这就说明了 j 值被重复修改后，会导致线程参数不对的现象。</p>
<p>解决办法：用一个 int 数组把需要传入到各个线程的参数缓存起来，尽量保证地址不一样。</p>
</p></div>
</p></div>
<div class="outline-3">
<h3 id="sec-1.3">结论</h3>
<div class="outline-text-3">
<p>传入线程的参数，应该尽量采用动态分配内存的方式来生成。否则如果采用临时变量，则随着变量生命周期的消逝，该变量的指针，很有可能会变成一个毫无意义的指针（或是被新的值覆盖，或是被成为一个遗留数）。</p>
<p>采用动态分配的变量作为线程启动时的参数，在线程结束后再销毁这个动态分配的变量，则是一个安全法则。</p>
</p></div>
</p></div>
]]></content:encoded>
			<wfw:commentRss>http://blog.waterlin.org/articles/cpp-multi-thread-passing-params-problems.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Log4Cxx 0.10.0 在 Linux 下退出程序时导致程序中断</title>
		<link>http://blog.waterlin.org/articles/log4cxx-10-exit-error-under-linux.html</link>
		<comments>http://blog.waterlin.org/articles/log4cxx-10-exit-error-under-linux.html#comments</comments>
		<pubDate>Tue, 17 Jan 2012 09:13:58 +0000</pubDate>
		<dc:creator>waterlin</dc:creator>
				<category><![CDATA[技术]]></category>
		<category><![CDATA[C++]]></category>

		<guid isPermaLink="false">http://blog.waterlin.org/articles/log4cxx-10-exit-error-under-linux.html</guid>
		<description><![CDATA[最近在写 Linux 程序的时候，碰到这样的问题：Log4Cxx 0.10.0 在 Linux 下退出程序时导致程序中断，即提示出现 segmentation fault 错误。 如果你用 gdb 调试，会提示如下信息： Program received signal SIGSEGV, Segmentation fault. 0x02fa68f3 in apr_vformatter () from /usr/lib/libapr-1.so.0 原因是因为 Log4Cxx 在退出时有非法的资源释放。 有一个解决办法：可以在程序退出时，显示地关闭 Log4Cxx 对象。 I have the same problem if I use log4cxx.AsyncAppender. I fixed the problem by calling log4cxx::LogManager::shutdown(); before the end of the process. It's not [...]]]></description>
			<content:encoded><![CDATA[<p>最近在写 Linux 程序的时候，碰到这样的问题：<a href="http://blog.waterlin.org/articles/log-chinese-logs-on-linux-using-log4cxx.html">Log4Cxx 0.10.0</a> 在 Linux 下退出程序时导致程序中断，即提示出现 segmentation fault 错误。</p>
<p>如果你用 gdb 调试，会提示如下信息：</p>
<pre>
Program received signal SIGSEGV, Segmentation fault.
0x02fa68f3 in apr_vformatter () from /usr/lib/libapr-1.so.0
</pre>
<p>原因是因为 <a href="http://blog.waterlin.org/articles/writing-cross-platform-cpp-code.html">Log4Cxx</a> 在退出时有非法的资源释放。</p>
<p>有一个解决办法：可以在程序退出时，显示地关闭 Log4Cxx 对象。</p>
<pre>
I have the same problem if I use log4cxx.AsyncAppender.
I fixed the problem by calling log4cxx::LogManager::shutdown(); before the end of the process.
It's not very clean but it works.
</pre>
<p>即<a href="http://comments.gmane.org/gmane.comp.apache.logging.log4cxx.user/2923">在程序退出时使用语句</a></p>
<pre>
log4cxx::LogManager::shutdown();
</pre>
<p>来清理 log4cxx，而不是让它自己来清理。</p>
<p>注意： <strong>需要在程序所有可能退出的地方，设置这一语句</strong> ，否则依然会有 segmentation fault 的问题。</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.waterlin.org/articles/log4cxx-10-exit-error-under-linux.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>编写跨平台的 C++ 代码</title>
		<link>http://blog.waterlin.org/articles/writing-cross-platform-cpp-code.html</link>
		<comments>http://blog.waterlin.org/articles/writing-cross-platform-cpp-code.html#comments</comments>
		<pubDate>Tue, 27 Dec 2011 06:38:32 +0000</pubDate>
		<dc:creator>waterlin</dc:creator>
				<category><![CDATA[技术]]></category>
		<category><![CDATA[C++]]></category>

		<guid isPermaLink="false">http://blog.waterlin.org/articles/writing-cross-platform-cpp-code.html</guid>
		<description><![CDATA[最近都在写一些跨 Windows 和 Linux 平台的 C++ 代码，略有心得，整理成文，备忘一下。 有关预编译指令 Visual Studio 会自动在源代码里添加 #pragma once 这个指令，在 Linux Gcc 编译器下应该怎么样处理类似的情况呢？ 维基百科上有一个权威说法： http://en.wikipedia.org/wiki/Pragma_once 所以，在编写跨平台的 C++ 代码时，最好使用下面这种方式来获得跨平台的特性： #pragma once #ifndef GRANDFATHER_H #define GRANDFATHER_H struct foo { int member; }; #endif /* GRANDFATHER_H */ 有关链接库工程的跨平台 Windows 下使用 __declspec(dllexport) 来标明一个动态链接库的函数接口，而在 Linux 下，则完全没有这个必要。 这个时候，如果动态链接库代码需要跨平台，应该怎么处理呢？ 你可以用如下宏来进行区分： #ifdef WIN32 #define EXPORT_XX __declspec(dllexport) #else #define EXPORT_XX [...]]]></description>
			<content:encoded><![CDATA[<p>最近都在写一些跨 Windows 和 Linux 平台的 C++ 代码，略有心得，整理成文，备忘一下。</p>
<div class="outline-3">
<h3 id="sec-1.1">有关预编译指令</h3>
<div class="outline-text-3">
<p>Visual Studio 会自动在源代码里添加</p>
<pre>
#pragma once
</pre>
<p>这个指令，在 Linux Gcc 编译器下应该怎么样处理类似的情况呢？</p>
<p><a href="http://en.wikipedia.org/wiki/Pragma_once">维基百科</a>上有一个权威说法：</p>
<pre>

http://en.wikipedia.org/wiki/Pragma_once
</pre>
<p>所以，在编写跨平台的 C++ 代码时，最好使用下面这种方式来获得跨平台的特性：</p>
<pre>
<span>#pragma</span> once
<span>#if</span><span>n</span><span>def</span> GRANDFATHER_H
<span>#define</span> <span>GRANDFATHER_H</span>

<span>struct</span> <span>foo</span>
{
    <span>int</span> <span>member</span>;
};

<span>#endif</span> <span>/* </span><span>GRANDFATHER_H */</span>
</pre>
</div></div>
<div class="outline-3">
<h3 id="sec-1.2">有关链接库工程的跨平台</h3>
<div class="outline-text-3">
<p><a href="http://cn.waterlin.org/Microsoft/visual-studio-dll-project.html">Windows 下使用 __declspec(dllexport) 来标明一个动态链接库的函数接口</a>，而在 Linux 下，则完全没有这个必要。</p>
<p>这个时候，如果动态链接库代码需要跨平台，应该怎么处理呢？</p>
<p>你可以用如下宏来进行区分：</p>
<pre>
<span>#ifdef</span> WIN32
<span>#define</span> <span>EXPORT_XX</span> <span>__declspec</span>(dllexport)
<span>#else</span>
<span>#define</span> <span>EXPORT_XX</span>
<span>#endif</span>
</pre>
</div></div>
<div class="outline-3">
<h3 id="sec-1.3">源代码的编码格式</h3>
<div class="outline-text-3">
<p>源代码的编码格式，最好统一用 GBK 或是 UTF-8，以避免不同编码器之间转换造成的乱码。</p>
</p></div>
</p></div>
<div class="outline-3">
<h3 id="sec-1.4">注意代码里的文件名大小写。</h3>
<div class="outline-text-3">
<p>Windows 里 include 一个头文件，你的大小写可以随便写。但是在 Linux 上，你得小心了，clsssa.h 你不能写成</p>
<pre>
#include "ClassA.h"
</pre>
<p>因为在 Linux 上，文件及目录名是大小写敏感的。</p>
</p></div>
</p></div>
<div class="outline-3">
<h3 id="sec-1.5">一些类型名称</h3>
<div class="outline-text-3">
<p>Windows 处理宽字符集与窄字符集采用的方法，是用宏定义来区分。比如说 TCHAR 在不同的工程下，属于不同的类型。</p>
<p>而在 Linux 下，则需要注意这些问题。为了让你的代码可移植性强。一定要少用 BOOL, TCHAR 这些类型，而要用原生态的 C/C++ 类型，比如说 bool, char 等。</p>
</p></div>
</p></div>
<div class="outline-3">
<h3 id="sec-1.6">有关 _tmain 等主函数问题。</h3>
<div class="outline-text-3">
<p>默认情况下，Visual Studio 新建的 Win32 Console 工程，全是类似于这样的。</p>
<pre>
<span>int</span> <span>_tmain</span>(<span>int</span> <span>argc</span>, <span>_TCHAR</span>* <span>argv</span>[])
{
}
</pre>
<p>这些代码，移植到 Linux 下面，就需要我们自己做一部分工作。</p>
<p>如果你在 Visual Studio 用的是 Unicode 编码的，则对应的 Linux 代码应该是另外一套。我则是用宏裁剪了两个主函数出来。如果你有什么更好的方法，可以跟我分享。</p>
</p></div>
</p></div>
<div class="outline-3">
<h3 id="sec-1.7">注意一些库在 Linux 和 Windows 平台下的不同表现</h3>
<div class="outline-text-3">
<p>虽然你的程序可能依赖大量的跨平台库，这些库号称是跨平台的，但是很有可能在不同的平台的表现，会有所不同。例如，<a href="http://blog.waterlin.org/articles/log-chinese-logs-on-linux-using-log4cxx.html">log4cxx 在 Linux 和 Windows 下就会有字符集设置的差别</a>。</p>
<p>你在编写跨平台代码的时候，就应该特别小心这些库的细微差别，及时调整。</p>
</p></div>
</p></div>
<div class="outline-3">
<h3 id="sec-1.8">后记</h3>
<div class="outline-text-3">
<p>以上是一些跨平台 C/C++ 代码编写的经验，备忘一下，也希望对大家有用。</p>
</p></div>
</p></div>
]]></content:encoded>
			<wfw:commentRss>http://blog.waterlin.org/articles/writing-cross-platform-cpp-code.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>log4cxx0.10.0 版本在 Linux 无法输出中文的问题</title>
		<link>http://blog.waterlin.org/articles/log-chinese-logs-on-linux-using-log4cxx.html</link>
		<comments>http://blog.waterlin.org/articles/log-chinese-logs-on-linux-using-log4cxx.html#comments</comments>
		<pubDate>Wed, 14 Dec 2011 08:16:46 +0000</pubDate>
		<dc:creator>waterlin</dc:creator>
				<category><![CDATA[技术]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[Linux]]></category>

		<guid isPermaLink="false">http://blog.waterlin.org/articles/log-chinese-logs-on-linux-using-log4cxx.html</guid>
		<description><![CDATA[最近在 Linux 下使用 log4cxx 库，使用的 log4cxx 版本为 0.10.0，结果无法显示中文日志信息。 这可怎么办呢？我不可能把中文日志全部一行一行替换为英文的，这可是一个非常傻B的举动。 经过研究，终于知道需要经过如下步骤才能让 log4cxx 在 Linux 下正常显示中文日志： 你可以先 locale 检查一下 Linux 终端环境是不是 zh_CN ； $ locale 如果你的是 en_US 之类的编码，则需要把 locale 设置为简体中文： $ export LC_ALL="zh_CN.UTF-8" 如果你的系统提示说没有安装本字符集，则需要用命令进行安装： $ sudo apt-get install language-pack-zh-hans 在程序里设置应用程序的 locale 和终端一样： LoggerPtr logger; log4cxx::PropertyConfigurator::configure("./log4cxx.properties"); logger= Logger::getLogger("test") ; logger-&#62;info(("Start logging")); setlocale(LC_ALL, "zh_CN.UTF-8"); 关键是最后这一句 setlocale，要设置得和终端一样，都是 zh_CN.UTF-8。 这样，你的程序就可以用 log4cxx0.10.0 [...]]]></description>
			<content:encoded><![CDATA[<p>最近在 Linux 下使用 log4cxx 库，使用的 log4cxx 版本为 0.10.0，结果无法显示中文日志信息。</p>
<p>这可怎么办呢？我不可能把中文日志全部一行一行替换为英文的，这可是一个非常傻B的举动。</p>
<p>经过研究，终于知道需要经过如下步骤才能让 log4cxx 在 Linux 下正常显示中文日志：</p>
<ol>
<li>你可以先 locale 检查一下 Linux 终端环境是不是 zh_CN ； </p>
<pre>
$ locale
</pre>
</li>
<li>如果你的是 en_US 之类的编码，则需要把 locale 设置为简体中文：
<pre>
$ export <span>LC_ALL</span>=<span>"zh_CN.UTF-8"</span>
</pre>
<p>如果你的系统提示说没有安装本字符集，则需要用命令进行安装：</p>
<pre>
$ sudo apt-get install language-pack-zh-hans
</pre>
</li>
<li>在程序里设置应用程序的 locale 和终端一样：
<pre>
LoggerPtr logger;
log4cxx::PropertyConfigurator::configure("./log4cxx.properties");
logger= Logger::getLogger("test") ;
logger-&gt;info(("Start logging"));
setlocale(LC_ALL, "zh_CN.UTF-8");
</pre>
<p>关键是最后这一句 setlocale，要设置得和终端一样，都是 zh_CN.UTF-8。</p>
</li>
</ol>
<p>这样，你的程序就可以用 log4cxx0.10.0 输出中文日志信息了。</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.waterlin.org/articles/log-chinese-logs-on-linux-using-log4cxx.html/feed</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Berkeley DB 头文件的类型定义与 MFC 冲突的问题</title>
		<link>http://blog.waterlin.org/articles/the-problem-to-compile-berkeley-db-with-mfc.html</link>
		<comments>http://blog.waterlin.org/articles/the-problem-to-compile-berkeley-db-with-mfc.html#comments</comments>
		<pubDate>Mon, 05 Sep 2011 09:37:57 +0000</pubDate>
		<dc:creator>waterlin</dc:creator>
				<category><![CDATA[技术]]></category>
		<category><![CDATA[C++]]></category>
		<category><![CDATA[Windows]]></category>

		<guid isPermaLink="false">http://blog.waterlin.org/articles/the-problem-to-compile-berkeley-db-with-mfc.html</guid>
		<description><![CDATA[在 Visual Studio 2008 MFC 工程中，利用 Berkeley DB 来构建数据存储引擎时，在编译 db.h 文件时出现编译错误，错误提示内容如下： 错误 3 error C2143: 语法错误 : 缺少"}"(在"("的前面) e:\water\berkeleydb\include\db.h 1226 微软的 MSDN 上有对 error C2143 的编译器错误进行解释，不过基本上没有太多可读性、可借鉴性，大意应该是一些宏定义、命名出错等。 最后，还是通过万能的 Google 大神找到了解答方法。错误的原因是 DB_TYPE, DB_UNKNOWN 类型已经在 MFC 系统头文件中被定义过，解决办法之一是在 db.h 中定义 DB_TYPE, DB_UNKNOWN 的语句之前加上如下语句即可： #ifdef DB_UNKNOWN #undef DB_UNKNOWN #endif #ifdef DBTYPE #undef DBTYPE #else #define DBTYPE BDBTYPE #endif 看来，C 和 [...]]]></description>
			<content:encoded><![CDATA[<p>在 Visual Studio 2008 MFC 工程中，利用 Berkeley DB 来构建数据存储引擎时，在编译 db.h 文件时出现编译错误，错误提示内容如下：</p>
<pre>
错误    3       error C2143: 语法错误 : 缺少"}"(在"("的前面)        e:\water\berkeleydb\include\db.h        1226
</pre>
<p>微软的 <a href="http://msdn.microsoft.com/en-us/library/0afb82ta.aspx">MSDN 上有对 error C2143 的编译器错误进行解释</a>，不过基本上没有太多可读性、可借鉴性，大意应该是一些宏定义、命名出错等。</p>
<p>最后，还是通过万能的 Google 大神找到了解答方法。错误的原因是 DB_TYPE, DB_UNKNOWN 类型已经在 MFC 系统头文件中被定义过，解决办法之一是在 db.h 中定义 DB_TYPE, DB_UNKNOWN 的语句之前加上如下语句即可：</p>
<pre>
<span>#ifdef</span> DB_UNKNOWN
<span>#undef</span> DB_UNKNOWN
<span>#endif</span>
<span>#ifdef</span> DBTYPE
<span>#undef</span> DBTYPE
<span>#else</span>
<span>#define</span> <span>DBTYPE</span> BDBTYPE
<span>#endif</span>
</pre>
<p>看来，C 和 C++ 混在一块，命名、类型定义真是一个大问题。以后碰到类似的问题，也可以采用类似的解决办法。</p>
<p>参考资料：</p>
<ol>
<li><a href="http://www.cppblog.com/fwxjj/archive/2010/08/10/122975.html">解决在vs2008的mfc工程中编译BerkeleyDB出错问题</a></li>
<li><a href="http://blog.csdn.net/dananhai/article/details/1694770">VS2005中的MFC程序使用BerkeleyDB</a></li>
<li><a href="http://msdn.microsoft.com/en-us/library/0afb82ta.aspx">MSDN Visual Studio 2010 Compiler Error C2143</a></li>
</ol>
]]></content:encoded>
			<wfw:commentRss>http://blog.waterlin.org/articles/the-problem-to-compile-berkeley-db-with-mfc.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>OpenCV 的 .Net 接口</title>
		<link>http://blog.waterlin.org/articles/using-opencv-with-c-sharp.html</link>
		<comments>http://blog.waterlin.org/articles/using-opencv-with-c-sharp.html#comments</comments>
		<pubDate>Fri, 05 Aug 2011 08:43:59 +0000</pubDate>
		<dc:creator>waterlin</dc:creator>
				<category><![CDATA[技术]]></category>
		<category><![CDATA[C++]]></category>

		<guid isPermaLink="false">http://blog.waterlin.org/articles/using-opencv-with-c-sharp.html</guid>
		<description><![CDATA[Emgu CV 是 OpenCV 跨平台的 C# 封装包，主要是为了方便在 C# 里使用 OpenCV 的库函数，下载和安装都很简单，新建一个 C# 控制窗口程序后，Hello World 例子代码如下： using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Drawing; using Emgu.CV; using Emgu.Util; using Emgu.CV.Structure; namespace OpenCVTester { class Program { static void Main(string[] args) { //The name of the window String win1 = "Test Window"; //Create the window [...]]]></description>
			<content:encoded><![CDATA[<p><a href="http://www.emgu.com/wiki/index.php/Main_Page">Emgu CV</a> 是 OpenCV 跨平台的 C# 封装包，主要是为了方便在 C# 里使用 OpenCV 的库函数，<a href="http://www.emgu.com/wiki/index.php/Download_And_Installation">下载和安装</a>都很简单，新建一个 C# 控制窗口程序后，Hello World 例子代码如下：</p>
<pre>
<span>using</span> <span>System</span>;
<span>using</span> <span>System</span>.Collections.Generic;
<span>using</span> <span>System</span>.Linq;
<span>using</span> <span>System</span>.Text;

<span>using</span> <span>System</span>.Drawing;
<span>using</span> <span>Emgu</span>.CV;
<span>using</span> <span>Emgu</span>.Util;
<span>using</span> <span>Emgu</span>.CV.Structure;

<span>namespace</span> <span>OpenCVTester</span>
{
    <span>class</span> <span>Program</span>
    {
        <span>static</span> <span>void</span> <span>Main</span>(<span>string</span>[] args)
        {
            <span>//</span><span>The name of the window
</span>            <span>String</span> <span>win1</span> = <span>"Test Window"</span>;

            <span>//</span><span>Create the window using the specific name
</span>            CvInvoke.cvNamedWindow(win1);

            <span>//</span><span>Create an image of 400x200 of Blue color
</span>            <span>using</span> (<span>Image</span>&lt;Bgr, Byte&gt; <span>img</span> = <span>new</span> <span>Image</span>&lt;Bgr, byte&gt;(400, 200, <span>new</span> <span>Bgr</span>(255, 0, 0)))
            {
                <span>//</span><span>Create the font
</span>                <span>MCvFont</span> <span>f</span> = <span>new</span> <span>MCvFont</span>(Emgu.CV.CvEnum.FONT.CV_FONT_HERSHEY_COMPLEX, 1.0, 1.0);
                <span>//</span><span>Draw "Hello, world." on the image using the specific font
</span>                img.Draw(<span>"Hello, world"</span>, <span>ref</span> <span>f</span>, <span>new</span> <span>Point</span>(10, 80), <span>new</span> <span>Bgr</span>(0, 255, 0));

                <span>//</span><span>Show the image
</span>                CvInvoke.cvShowImage(win1, img.Ptr);
                <span>//</span><span>Wait for the key pressing event
</span>                CvInvoke.cvWaitKey(0);
                <span>//</span><span>Destory the window
</span>                CvInvoke.cvDestroyWindow(win1);
            }
        }
    }
}
</pre>
<p>这里需要注意的是，如果用 Visual Studio 2008 来调试上面的代码，则记得要把 OpenCV 相关的动态链接库放到你测试工程的这个目录里：</p>
<pre>
\bin\Debug
</pre>
<p>否则在跑到下面这句代码</p>
<pre>
CvInvoke.cvNamedWindow(win1);
</pre>
<p>的时候，就会弹出一个莫名其妙的出错框，提示如下错误：</p>
<pre>
未处理的"System.TypeInitializationException"类型的异常出现在 OpenCVTester.exe 中。

其他信息: "Emgu.CV.CvInvoke"的类型初始值设定项引发异常
</pre>
<p>看来，C#调试时的程序动态链接库读取位置，还比较特殊呀~~</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.waterlin.org/articles/using-opencv-with-c-sharp.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>用 OpenCV 读取视频的指定帧序号视频片断</title>
		<link>http://blog.waterlin.org/articles/opencv-jump-to-video-position.html</link>
		<comments>http://blog.waterlin.org/articles/opencv-jump-to-video-position.html#comments</comments>
		<pubDate>Sat, 09 Jul 2011 14:29:48 +0000</pubDate>
		<dc:creator>waterlin</dc:creator>
				<category><![CDATA[技术]]></category>
		<category><![CDATA[C++]]></category>

		<guid isPermaLink="false">http://blog.waterlin.org/articles/opencv-jump-to-video-position.html</guid>
		<description><![CDATA[用 OpenCV 来读取视频，经常需要从指定帧序号的片断开始读取，这个时候，就需要用 cvSetCaptureProperty 结合参数 CV_CAP_PROP_POS_FRAMES 来设定，例子代码如下： bool PickSomeFrames(const char* filename, int start, int end, char* savePath) { CvCapture* capture = cvCaptureFromAVI(filename); //读取视频文件 cvSetCaptureProperty(capture, CV_CAP_PROP_POS_FRAMES, start); int count = start; while( cvGrabFrame(capture) &#38;&#38; count &#60;= end ) { IplImage* pFrame = cvRetrieveFrame(capture);// 获取当前帧 char test[100]; sprintf(test,"%s\\%d%s",savePath,count,".jpg"); cvSaveImage(test,pFrame); count++; } cvReleaseCapture(&#38;capture); return false; } 以上这种方法，支持用多线程的方式，来同时读写视频不同帧序号开始的片断。以上这些代码，在采用多线程来加速视频处理时，特别有用。]]></description>
			<content:encoded><![CDATA[<p>用 OpenCV 来读取视频，经常需要从指定帧序号的片断开始读取，这个时候，就需要用 <strong>cvSetCaptureProperty</strong> 结合参数 <strong>CV_CAP_PROP_POS_FRAMES</strong> 来设定，例子代码如下：</p>
<pre>
<span>bool</span> <span>PickSomeFrames</span>(<span>const</span> <span>char</span>* <span>filename</span>, <span>int</span> <span>start</span>, <span>int</span> <span>end</span>, <span>char</span>* <span>savePath</span>)
{
    <span>CvCapture</span>* <span>capture</span> = cvCaptureFromAVI(filename);  <span>//</span><span>读取视频文件
</span>
    cvSetCaptureProperty(capture, CV_CAP_PROP_POS_FRAMES, start);

    <span>int</span> <span>count</span> = start;
    <span>while</span>( cvGrabFrame(capture) &amp;&amp; count &lt;= end )
    {
        <span>IplImage</span>* <span>pFrame</span> = cvRetrieveFrame(capture);<span>// </span><span>获取当前帧
</span>
        <span>char</span> <span>test</span>[100];
        sprintf(test,<span>"%s\\%d%s"</span>,savePath,count,<span>".jpg"</span>);
        cvSaveImage(test,pFrame);

        count++;
    }

    cvReleaseCapture(&amp;capture);

    <span>return</span> <span>false</span>;
}
</pre>
<p>以上这种方法，支持用多线程的方式，来同时读写视频不同帧序号开始的片断。以上这些代码，在采用多线程来加速视频处理时，特别有用。</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.waterlin.org/articles/opencv-jump-to-video-position.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>wsprintf 缓冲区的字符数上限</title>
		<link>http://blog.waterlin.org/articles/the-limitation-of-wsprintf-buffer.html</link>
		<comments>http://blog.waterlin.org/articles/the-limitation-of-wsprintf-buffer.html#comments</comments>
		<pubDate>Mon, 25 Oct 2010 05:57:29 +0000</pubDate>
		<dc:creator>waterlin</dc:creator>
				<category><![CDATA[技术]]></category>
		<category><![CDATA[C++]]></category>

		<guid isPermaLink="false">http://blog.waterlin.org/articles/the-limitation-of-wsprintf-buffer.html</guid>
		<description><![CDATA[最近碰到一个一直以来没有注意的问题，我习惯地使用 wsprintf 来格式化输出字符串，可是，最近在一次收到 http 请求回来的数据后，只截取到了大约一半的字符串。 很奇怪的是，用 lstrcpy 来把结果复制并生成新的字符串，却可以完整的复制。 仔细查了一下 MSDN，发现原来有这么一句话： To use buffers larger than 1024 bytes, use _snwprintf. For more information, see the documentation for the C run-time library. 原来，wsprintf 的缓冲区有 1024 个字符串的上限，看来以后要注意这个问题了。]]></description>
			<content:encoded><![CDATA[<p>最近碰到一个一直以来没有注意的问题，我习惯地使用 wsprintf 来格式化输出字符串，可是，最近在一次收到 http 请求回来的数据后，只截取到了大约一半的字符串。</p>
<p>很奇怪的是，用 lstrcpy 来把结果复制并生成新的字符串，却可以完整的复制。</p>
<p>仔细查了一下 <a href="http://msdn.microsoft.com/en-us/library/ms647550(VS.85).aspx">MSDN</a>，发现原来有这么一句话：</p>
<pre>
To use buffers larger than 1024 bytes, use _snwprintf. For more information, see the documentation for the C run-time library.
</pre>
<p>原来，wsprintf 的缓冲区有 1024 个字符串的上限，看来以后要注意这个问题了。</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.waterlin.org/articles/the-limitation-of-wsprintf-buffer.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Visual Studio 2008 的颜色主题设置</title>
		<link>http://blog.waterlin.org/articles/set-style-theme-for-visual-studio.html</link>
		<comments>http://blog.waterlin.org/articles/set-style-theme-for-visual-studio.html#comments</comments>
		<pubDate>Fri, 06 Nov 2009 06:05:38 +0000</pubDate>
		<dc:creator>waterlin</dc:creator>
				<category><![CDATA[技术]]></category>
		<category><![CDATA[C++]]></category>

		<guid isPermaLink="false">http://blog.waterlin.org/articles/set-style-theme-for-visual-studio.html</guid>
		<description><![CDATA[默认情况下 Visual Studio 2008 的主题是白底黑字，这样看久了代码，很累。 还好，Visual Studio 提供了强大的自定制功能，我们可以随意设置字体的大小与颜色。当然，最方便的，还是使用其他人配好的颜色，比如说这个 Dark Visual Studio 主题就很不错。 要导入该设置，只需要在 Visual Studio 里的菜单 Tools ==&#62; Import and Export Settings… 里进行导入。如果你对配置进行了若干自定义，则可以用该导出功能进行保存与备份。 原创文章，如转载请注明：转载自细节之锤 [ http://blog.WaterLin.org/ ] Copyright © WaterLin.org. All rights reserved.]]></description>
			<content:encoded><![CDATA[<p>默认情况下 Visual Studio 2008 的主题是白底黑字，这样看久了代码，很累。</p>
<p>还好，Visual Studio 提供了强大的自定制功能，我们可以随意设置字体的大小与颜色。当然，最方便的，还是使用其他人配好的颜色，比如说这个 <a href="http://www.agileprogrammer.com/dotnetguy/archive/2006/09/07/19030.aspx">Dark Visual Studio</a> 主题就很不错。</p>
<p>要导入该设置，只需要在 Visual Studio 里的菜单 Tools ==&gt; Import and Export Settings… 里进行导入。如果你对配置进行了若干自定义，则可以用该导出功能进行保存与备份。</p>
<p>原创文章，如转载请注明：转载自细节之锤 [ <a href="http://blog.WaterLin.org/">http://blog.WaterLin.org/</a> ]</p>
<p>Copyright © WaterLin.org. All rights reserved.</p>
]]></content:encoded>
			<wfw:commentRss>http://blog.waterlin.org/articles/set-style-theme-for-visual-studio.html/feed</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

