包含来自C#的.dll

时间:2015-03-02 03:12:37

标签: c# pinvoke dllimport

我有图书馆说tenslib.h,我已使用visual Studio 10 C将其更改为tensLibs.dll(我已使用this)。

我想用C#窗口表单应用程序打开它。我建立并成功。但是当我运行应用程序时,出现错误:

  

类型' System.DllNotFoundException'未处理的异常发生在WindowsFormsCSharpApplication3.exe

中      

其他信息:无法加载DLL' tensLibs.dll':找不到指定的模块。 (HRESULT异常:0x8007007E)

这是我的程序的快照

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices; //for export dll


namespace WindowsFormsCSharpApplication3
{
public partial class Form1 : Form
{
    [DllImport("tensLibs.dll", EntryPoint = "tens_init")]
    public static extern int tens_init([MarshalAsAttribute(UnmanagedType.LPStr)]string port);

 private void button2_Click(object sender, EventArgs e)
    {
        if (tens_init("COM8") == 1)
            label2.Text="Com 8 is initiated";
        else
            label2.Text="Com 8 does not exists";
    }
}
}

我在文件夹中添加了tensLibs.dll但仍然出现错误。我试图将dll文件的引用添加到项目中,但无法添加。

我使用了dependdency walker程序找到我需要{。}}和Kernel32.dll的.dll的根,并且我已经添加到我的文件夹中,错误仍然存​​在。

我在x86中运行。

这是我的Tens.h来源

MSVCR100d.dll

而对于tens.c来说,我只需要把tens_init()

#ifndef TENSLIB_H_
#define TENSLIB_H_

#ifdef __cplusplus
 extern "C" {
#endif

int  tens_init( char* port );
void tens_shutdown( void );


int tens_tutor( unsigned char finger );
void tens_shutdown( void );

int tens_settarget( unsigned char id );

int tens_enable( unsigned char supply_on, unsigned char bridge_on );
int tens_power( unsigned char power );
int tens_freq( unsigned char freq );
int tens_control( unsigned char power, unsigned char freq );

int tens_chargerate( unsigned char rate );
int tens_tunepower( unsigned char up );
int tens_writeconfig( void );
int tens_changeid( unsigned char id );

int tens_envs( unsigned char distance );
int tens_envsconf( unsigned char pmin, unsigned char pmax, unsigned char fmin, unsigned char fmax );

int tens_tutor( unsigned char finger );

int tens_garbage( void );


#ifdef __cplusplus
}
#endif

#endif

任何人都可以告诉我这是什么问题,我该如何解决?

谢谢。

1 个答案:

答案 0 :(得分:2)

互操作有两个问题。

<强> 1。缺少依赖

System.DllNotFoundException异常告诉您无法找到您的DLL或其中一个依赖项。将DLL放在与可执行文件相同的目录中。安装DLL的任何运行时依赖项,例如MSVC运行时。如果您没有在目标计算机上使用DLL的VS版本,则可能需要编译DLL的发布版本。

<强> 2。调用约定不匹配

DLL导出cdecl函数。您导入为stdcall。 DllImport属性需要指定正确的调用约定:

[DllImport("tensLibs.dll", CallingConvention = CallingConvention.Cdecl)]

一边说。 C中的布尔测试如下。零是错误的,其他一切都是真的。不要在C#代码中测试== 1。测试!= 0。但是,使用bool作为tens_init的返回类型更简单,让编组人员为您完成工作。