VC++で作成したDLLの使用E
2010/07/09
DLL作成E で作成したDLLを、C# で利用してみます。
◆環境
OS |
Windows XP Professional Version 2002 Service Pack 3 |
VC |
Microsoft Visual C# 2008 91179-136-7480673-60690 |
プロジェクトを作り、DLLImportを書きます。
Program.cs
|
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:
29:
30:
31:
32:
33:
34:
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace ConsoleApplication6
{
class VCDLLTest6
{
[DllImport("VCDLLTest6.dll")]
public static extern int myLength(string a);
[DllImport("VCDLLTest6.dll")]
public static extern int myChar8Change(string a);
}
class Program
{
static void Main(string[] args)
{
string strbuf = "123456789";
Console.WriteLine( "myLength="
+ VCDLLTest6.myLength(strbuf)
);
Console.WriteLine("myChar8Change="
+ VCDLLTest6.myChar8Change(strbuf)
);
Console.WriteLine("strbuf=" + strbuf);
}
}
}
|
|
実行してみます。
myLength=9
myChar8Change=4
strbuf=123456789
続行するには何かキーを押してください . . .
myLength の戻り値が 9 で、これは合っています。
myChar8Change の戻り値が 4 です。
これは DLL 内で "abcd" という 4文字の文字列をセットし strlen した値を返しているので 4 は合っていそうです。
でも strbuf の値は更新されていませんでした。
DLL に渡す strbuf は、実際は参照を渡さなければなりません。
参照渡しの場合、StringBuilderを使用すると良いようです。
Program.cs
|
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:
29:
30:
31:
32:
33:
34:
35:
|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Runtime.InteropServices;
namespace ConsoleApplication6
{
class VCDLLTest6
{
[DllImport("VCDLLTest6.dll")]
public static extern int myLength(string a);
[DllImport("VCDLLTest6.dll")]
public static extern int myChar8Change(StringBuilder a);
}
class Program
{
static void Main(string[] args)
{
StringBuilder strbuf = new StringBuilder();
strbuf.Append("123456789");
Console.WriteLine("myLength="
+ VCDLLTest6.myLength(strbuf.ToStrin
g())
);
Console.WriteLine("myChar8Change="
+ VCDLLTest6.myChar8Change(strbuf)
);
Console.WriteLine("strbuf=" + strbuf);
}
}
}
|
|
実行してみます。
myLength=9
myChar8Change=4
strbuf=abcd
続行するには何かキーを押してください . . .
strbuf に "abcd" が設定されました。
▲ PageTop ■ Home
Copyright (C) 2012 ymlib.com