スキップしてメイン コンテンツに移動

投稿

ラベル(.Net)が付いた投稿を表示しています

C#でMarshalクラスを使ってbyte配列から構造体を生成する方法

C#の通信プログラムでbyte配列を読み込んで、構造体(struct)を生成したいときにサンプルコードの紹介です。 Genericsを使って任意の構造体をbyte配列から生成できるようにしています。 public static T ReadAsStruct < T > ( this byte [ ] bytes , int startIndex ) where T : struct { // GCHandle.Allocクラスを使ってメモリ上のデータがガーベッジコレクタの対象にならないようにする。 var handle = GCHandle . Alloc ( bytes , GCHandleType . Pinned ) ; try { // Marshalクラスのメソッドを使って、byte配列のIntPtr(ポインタ)を取得。 var ptr = Marshal . UnsafeAddrOfPinnedArrayElement ( bytes , startIndex ) ; // IntPtrで指定した位置のbyte配列から構造体を生成。 return ( T ) Marshal . PtrToStructure ( ptr , typeof ( T ) ) ; } finally { // 重要!!必ずGCHandleを開放して、再びbyte配列がガーベッジコレクタの対象になるようにする。 handle . Free ( ) ; } } ちょっと考察 ■ パフォーマンス 毎回GCHandle.Alloc, Freeを行う分、パフォーマンスのオーバーヘッドが発生します。パフォーマンスが気になる場合は、GCHandle.Alloc, Freeの間に、複数の構造体を生成するようにするとよいかもしれません。 ■ 他の書き方 startIndexがいつもゼロの場合、下記の部分は、 var ptr = Marshal . UnsafeAddrOfPinnedArrayElem

C#: Create Indexed PNG Using System.Windows.Media.BitmapSource with Pre-defined Palettes in BitmapPalettes Class

Creating Indexed PNG in C# In C#, there are mainly two namespaces to creating image... System.Drawing namespace System.Windows.Media namespace I've already written the post for creating indexed png using System.Drawing namespace classes - Create Indexed PNG Using C# .Net . So, in this post, I will show you how to create indexed png using classes under System.Windows.Media namespace. Preparation for Using Classes Under System.Windows.Media You need to add following dlls to your project reference in order to handle images using classes under System.Windows.Media. PresentationCore.dll Xaml.dll WindowsBase.dll Creating Palette Based Indexed Image If you would like to create indexed png, first of all, you should create color palette which can hold max 256 colors. Creating color palette is trivial. Please see the below example code: var colors = new List<Color>(); colors.Add(Color.FromRgb(255, 0, 0)); // 0 - red colors.Add(Color.FromRgb(0, 255, 0)); // 1 -

Create Indexed PNG Using C# .Net

Currently I am working on optimizing image size. In this post, I will demonstrate the C# code for creating indexed png image. The code might not be perfect yet, but hope this code will give you some hints ;) A few things I am struggling with while I am writing the example code: Palette: you should take ColorPalette from Bitmap, modify the ColorPalette object and set buck it to the Bitmap object. BitmapData.Stride is often bigger than BitmapData.Width. You should be careful to check both values difference when you manipulating the image array index. The example code uses classes in System.Drawing namespace. But looks there is another option to manipulate image in C# .Net - System.Windows.Media namespace. C# Source Code for Creating Indexed PNG The following implementation of CreateIndexedPng method is able to take only non-indexed image like Format24bppRgb or Format32bppArgb. (I might add other image formats in future.) If the source image has only 2 colors, we can use For

JSON

最近 JSON 形式のファイルを扱うことが多く、色んなライブラリを触ってきました。 どれも甲乙つけがたいですが、とりあえずいくつか紹介します。(そのうちコードサンプルを交えたレビューも書きたいと思います。) .Net用のライブラリ Json.NET : stackoverflowではかなり強く推薦されていました。 Jayrock Java用のライブラリ Jackson : これが一番使いやすかったです。annotationの機能はかなり便利です。 XStream : XMLのシリアライゼーションで有名ですが、JSONでも使えます。残念ながらまだ試したことはありません。。。 JSON Tools stringtree.org Json-lib : これも使ったことがあります。多機能すぎて、個人的には使用法を理解するのに時間がかかりました。ちょっと癖があると思います。

Microsoft Outlookの.msgファイルをC#で読みこむ方法

.NetライブラリのMicrosoft.Office.Interio.Outlookを使う ディスクなどに保存された.msgファイルを読み込むことは難しいのではないかと思います。 未検証です。 CodeProjectで公開されているライブラリを使う このページ で公開されているプロジェクトファイルを使えばできそうです。こういうものをさくっと作れるのはうらやましいですね。 この記事は書き途中です。よりよい方法が見つかり次第更新します!

Test Tools for .Net

Unit Testing Framework for .Net NUnit @ITのNunitの解説ページ Code Coverage Tool for .Net NCover :I think this is the famous one rather than the one below which has the same name. The problem is this tool is not free :(. NCover : Free open source code coverage tool for .Net. partcover : This is the alternative tool of NCover. I'll try to use it ;). ReportGenerator : This can generate cool and readble code coverage report.

C++.NetでのThreadの実行方法

C++.NetでのThreadの実行方法です。C#でThreadの使い方を知っていれば、理解はしやすいと思います。 using namespace System; using namespace System::Threading; ref class Work { public: static void DoWork() { Console::WriteLine( "Static thread procedure." ); } void DoMoreWork() { Console::WriteLine( "Instance thread procedure."); } }; int main(array ^args) { Work ^w = gcnew Work; ThreadStart ^start = gcnew ThreadStart(w, &Work::DoMoreWork); Thread ^t = gcnew Thread(start); t->Start(); Console::ReadLine(); return 0; }

.Net用のLogツール

log4net .Net用の強力なLoggingツールです。Log4Jの.Net版といったところでしょうか。 解説サイト O'Reillyの WindowsDevCenter.com の このページ が大変参考になります。 @ITの このページ も参考になります。

Spring.Net

Spring.Net .Net版のSpring Frameworkです。基本的な使い方はJava版の本家Springに準じています。 日本語では こちら の記事が参考になります。

C# and .Net Tips

C#でのリフレクション Dynamically load a class and execute a method in .NET Assembly Load Assembly C# / CSharp Tutorial オープンソースの.Netプラットフォーム Mono : Cross Platform + Open Source .Net environment Microsoft C# でのHTML構文解析 Microsoft C# でのHTML構文解析 Flashを.Net環境 で扱うためのヒント CodeZine の このページ が参考になります。 .Net環境で時間を計測する方法 処理時間を正確に計測するには?[2.0のみ、C#、VB] ImageAnimator C#でGIF Animeを再生できるクラス .NetのApp.configファイル アプリケーション構成ファイル(App.config)、 Web構成ファイル(Web.config)にカスタム構成セクションを追加する C#におけるCastとAs演算子を用いた型変換の性能差 Type casting impact over execution performance in C# .Net用のメールライブラリ JMail.NET 解析ツール FxCop :.Netでコンパイルされたdllを解析するためのツールです。 .Net, C# に関する便利なサイト DOBON.NET 連載:改訂版 C#入門 C# Certification, Development, and Training .Net Tips C# ソースコード集 :色々サンプルがありますので、参考になると思います。 C#とVB.NETの入門サイト

ソースコードの難読化ツール

.Net Nandoku .Net Reflector Dotfuscator Community Edition :2003年の記事ですが@ITに .NET逆コンパイラと コードを難読化するDotfuscator の記事があります。 Java ProGuard Javascript このページ によくまとまっています。 「成分解析」研究室 さんの このページ に非常によくまとまっています。 難読化手法については ここ によくまとまっています。