关于.NET应用程序间数据的共享
.NET为了安全起见,框架并没有提供应用程序间的数据共享功能。然而,我们的项目中,经常需要跨进程间的数据共享,只能采用一些.NET以外的东西去实现此目的。
今天我给大家介绍一种跨进程间数据共享的方法。
在CodeProject站点中找到了一个VC的源码,它是通过data_seg来实现数据的共享。
(http://www.codeproject.com/dll/data_seg_share.asp)但是,它是实现VC应用程序间的数据共享,需要进行简单的修改之后才能正常使用。
下面的就是我修改之后的内容。
1、 TestMemorySpace.def
如果VC的dll想让VB,.NET等应用程序正常调用,必须将自身的函数EXPORTS出来,因此需要在def文件中进行声明。
EXPORTS
; Explicit exports can go here
GetValueString @1
SetValueString @2
2、重新编译dll
修改完上面的内容之后,就可以重新编译dll了。
3、测试
新建一个.NET的应用程序,在窗体上放一个文本框和两个按钮,编写如下的代码。
Imports System.Runtime.InteropServices
Imports Microsoft.VisualBasic
Public Class Form1Class Form1
<DllImport("TestMemorySpace.dll", EntryPoint:="SetValueByte", SetLastError:=True, _
CharSet:=CharSet.Unicode, ExactSpelling:=True, _
CallingConvention:=CallingConvention.StdCall)> _
Public Shared Sub SetValueByte()Sub SetValueByte(ByVal bytes() As Byte) _
' Leave the body of the function empty.
End Sub
<DllImport("TestMemorySpace.dll", EntryPoint:="GetValueByte", SetLastError:=True, _
CharSet:=CharSet.Unicode, ExactSpelling:=True, _
CallingConvention:=CallingConvention.StdCall)> _
Public Shared Sub GetValueByte()Sub GetValueByte(ByVal bytes() As Byte) _
' Leave the body of the function empty.
End Sub
<DllImport("TestMemorySpace.dll", EntryPoint:="SetValueString", SetLastError:=True, _
CharSet:=CharSet.Unicode, ExactSpelling:=True, _
CallingConvention:=CallingConvention.StdCall)> _
Public Shared Sub SetValueString()Sub SetValueString(ByVal a() As Byte) _
' Leave the body of the function empty.
End Sub
<DllImport("TestMemorySpace.dll", EntryPoint:="GetValueString", SetLastError:=True, _
CharSet:=CharSet.Unicode, ExactSpelling:=True, _
CallingConvention:=CallingConvention.StdCall)> _
Public Shared Sub GetValueString()Sub GetValueString(ByVal a() As Byte) _
' Leave the body of the function empty.
End Sub
Private Sub Form1_Load()Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub

Private Sub Button1_Click()Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim bytes() As Byte
bytes = System.Text.Encoding.Default.GetBytes(TextBox1.Text.ToString)
SetValueString(bytes)
End Sub

Private Sub Button2_Click()Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim bytes(4096) As Byte
GetValueString(bytes)
TextBox1.Text = System.Text.Encoding.Default.GetString(bytes)
End Sub
End Class
本文介绍了一种跨进程数据共享的方法,通过修改VC的源码并导出特定函数,使得DLL能在不同.NET应用间共享数据。文章提供了具体的修改步骤及.NET程序调用示例。
7487

被折叠的 条评论
为什么被折叠?



