VisualStudio2017 C#(.Net Core 2.0)で、MeCab(0.996)のlibmecab.dllを参照し形態素解析を行う場合、下記のソースでMeCabの解析結果を得ることができる。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | using System; using System.Runtime.InteropServices; class Program { const string MECAB_LIB_PATH = @"C:\Program Files (x86)\MeCab\bin\libmecab.dll"; [DllImport(MECAB_LIB_PATH, CallingConvention = CallingConvention.Cdecl)] extern static IntPtr mecab_new2(String arg); [DllImport(MECAB_LIB_PATH, CallingConvention = CallingConvention.Cdecl)] extern static IntPtr mecab_sparse_tostr(IntPtr ptrMeCab, String arg); [DllImport(MECAB_LIB_PATH, CallingConvention = CallingConvention.Cdecl)] extern static void mecab_destroy(IntPtr ptrMeCab); static void Main(string[] args) { try { var ptrMeCab = mecab_new2(""); var ptrResult = mecab_sparse_tostr(ptrMeCab, "テストデータ"); var strResult = Marshal.PtrToStringAnsi(ptrResult); mecab_destroy(ptrMeCab); } catch (Exception ex) { System.Diagnostics.Trace.WriteLine(ex.Message); } } } |
strResult変数には、下記実行結果が出力される。
1 2 3 | "テスト\t名詞,サ変接続,*,*,*,*,テスト,テスト,テスト\nデータ\t名詞,一般,*,*,*,*,データ,データ,データ\nEOS\n" |
libmecab.dllを参照しているプロジェクトはx86で実行する必要がある。 .Net Core固有の問題から、下記手順を経ないとデバッグ実行時にアプリケーションが即落ちて原因が分からずにはまる。 1、Visual Studio 2017 をインストールしても、x86版の.NetCore SDKはインストールされないので、別途、ダウンロードしてインストールしておく。
2、プロジェクトのプラットフォームをx86に変更しても、デフォルトのデバッグ実行はx64版の.NetCore SDKで実行され、x86アプリをx64のSDKで実行しようとしてプリケーションが落ちるので、.csprojファイルをメモ帳で開き、下記を追記することで、x86プラットフォームの場合は、x86版.NetCore SDK上で実行するよう変更できる。
1 2 3 | $(MSBuildProgramFiles32)\dotnet\dotnet $(ProgramW6432)\dotnet\dotnet |
下記は追記した後の、.csprojファイル全体のサンプル。
<Project Sdk=”Microsoft.NET.Sdk”>
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp2.0</TargetFramework>
<StartupObject>MeCabテストCore.Program</StartupObject>
<RunCommand Condition=”‘$(PlatformTarget)’ == ‘x86′”>
$(MSBuildProgramFiles32)\dotnet\dotnet</RunCommand>
<RunCommand Condition=”‘$(PlatformTarget)’ == ‘x64′”>
$(ProgramW6432)\dotnet\dotnet</RunCommand>
</PropertyGroup>
<PropertyGroup Condition=”‘$(Configuration)|$(Platform)’==’Debug|AnyCPU'”>
<PlatformTarget>x86</PlatformTarget>
<RunCommand Condition=”‘$(PlatformTarget)’ == ‘x86′”>
$(MSBuildProgramFiles32)\dotnet\dotnet</RunCommand>
<RunCommand Condition=”‘$(PlatformTarget)’ == ‘x64′”>
$(ProgramW6432)\dotnet\dotnet</RunCommand>
</PropertyGroup>
</Project>
コメント