在SQL Server中从VB CLR UDF调用非托管C DLL



我正试图集成现有的C DLL(非管理显然),实现模糊匹配,到SQL Server作为用户定义的函数(UDF)。UDF是用CLR VB项目实现的。我已经使用这个C代码近20年,在文本文件上做字符串匹配没有任何障碍。它已经在几乎所有的平台上进行了编译,并且从未崩溃或给出错误的结果。永远。直到现在。

UDF在SQL SELECT语句中的用法如下:

SELECT Field FROM Table WHERE xudf_fuzzy('doppler effect', Field) = 1;

xudf_fuzzy(Param1, Param2) = 1是奇迹发生的地方。Param1是我们试图匹配的线索词,而Param2是要测试的表中的字段。如果匹配在一定数量的错误内成功,则UDF返回1,否则返回0。到目前为止一切顺利。

下面是定义模糊UDF并调用C DLL的CLR代码:

Imports System
Imports System.Data
Imports System.Data.SqlClient
Imports System.Data.SqlTypes
Imports System.Text
Imports Microsoft.SqlServer.Server
Imports System.Runtime.InteropServices

Partial Public Class fuzzy
<DllImport("C:UsersAdministratorDesktopfuzzy64.dll", _
           CallingConvention:=CallingConvention.StdCall)> _
Public Shared Function setClue(ByRef clue As String, ByVal misses As Integer) As       Integer
End Function
<DllImport("C:UsersAdministratorDesktopfuzzy64.dll", _
           CallingConvention:=CallingConvention.StdCall)> _
Public Shared Function srchString(ByRef text1 As String) As Integer
End Function

<Microsoft.SqlServer.Server.SqlFunction()> Public Shared Function _
        xudf_fuzzy(ByVal strSearchClue As SqlString, ByVal strStringtoSearch As SqlString) As Long
    Dim intMiss As Integer = 0
    Dim intRet As Integer
    Static Dim sClue As String = ""
    xudf_fuzzy = 0
    ' we only need to set the clue whenever it changes '
    If (sClue <> strSearchClue.ToString) Then
        sClue = strSearchClue.ToString
        intMiss = (Len(sClue)  4) + 1
        intRet = setClue(sClue, intMiss)
    End If
    ' return the fuzzy match result (0 or 1) '
    xudf_fuzzy = srchString(strStringtoSearch.ToString)
End Function

这里是被调用的C代码的前端。STRCT是所有全局存储所在的地方。

fuzzy.h
typedef struct {
short int INVRT, AND, LOWER, COMPL, Misses;
long int num_of_matched;
int D_length;
unsigned long int endposition, D_endpos;
unsigned long int Init1, NOERRM;
unsigned long int Mask[SYMMAX];
unsigned long int Init[MaxError];
unsigned long int Bit[WORDSIZE+1];
unsigned char prevpat[MaxDelimit];
unsigned char _buffer[Max_record+Max_record+256];
unsigned char _myPatt[MAXPAT];
} SRCH_STRUCT;

fuzzy.c
#include <sys/types.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <wtypes.h>
#include <time.h>
#include "fuzzy.h"
// call exports
__declspec(dllexport) int CALLBACK setClue(char**, int*);
__declspec(dllexport) int CALLBACK srchString(char**);
SRCH_STRUCT STRCT = { 0 };
int cluePrep(unsigned char []);
int srchMin(unsigned char [], int);
BOOL APIENTRY DllMain( HANDLE hModule, DWORD  ul_reason_for_call, LPVOID lpReserved )
{
    switch (ul_reason_for_call)
    {
        case DLL_PROCESS_ATTACH:
        case DLL_THREAD_ATTACH:
        case DLL_THREAD_DETACH:
        case DLL_PROCESS_DETACH:
        break;
    }
    return TRUE;
}
int CALLBACK setClue(char **pattern, int *misses)
{
    int i;
    unsigned char *p;
    // code to do initialization stuff, set flags etc. etc.    
        STRCT.Misses = (int)misses;
        p = &(STRCT._myPatt[2]);
        STRCT._myPatt[0] = 'n';
        STRCT._myPatt[1] = SEPCHAR;
        strcpy((char *)p, *pattern);
        //blah blah
    // end setup stuff
    i = cluePrep(STRCT._myPatt);
    return 0;
}

int CALLBACK srchString(char **textstr)
{
    int res,i = Max_record;
    unsigned char c;
    char *textPtr = *textstr;
    STRCT.matched = 0;
    //clean out any non alphanumeric characters while we load the field to be tested
    while ((c = *textPtr++)) if ( isalpha(c) || isdigit(c) || c == ' ' ) STRCT._buffer[i++] = c;
    STRCT._buffer[i] = 0;
    // do the search
    res =  srchMin(STRCT.pattern, STRCT.Misses);
    if (res < 0) return res;
    return STRCT.matched;
}

链接到的运行库是:多线程DLL (/MD)

调用约定为:__cdecl (/Gd)

这就是奇怪的地方。如果我有一个常规的。net应用程序(未显示的代码),它从测试数据库中获取整个记录集,并通过调用此DLL来调用模糊匹配,每次迭代所有记录,我每次都会得到正确的结果。

如果我使用上面所示的SQL语句对测试数据库使用CLR UDF应用程序,而只使用一个线程(单核VM),我每次都能得到正确的结果。

当这个DLL在多核机器上以CLR UDF模式使用时,一些结果是错误的。结果总是有点偏差,但并不一致。

292条记录应该匹配并在前两个测试用例中执行。

在CLR UDF多线程情况下,返回的结果将是273、284、298、290等。

C DLL中的所有存储都是字符数组。没有使用内存分配。这也是我的理解,如果SQL Server在多线程模式下使用这个CLR应用程序,线程都被分配了自己的数据空间。

我需要以某种方式"针"的字符串之前,我把它们发送到C DLL?

pin不是你的问题,你的C代码不是线程安全的。C代码使用全局变量STRCT。该全局变量只有一个实例,它将在所有线程之间共享。每个线程将用不同的值更新STRCT变量,这将导致不正确的结果。

你必须重构C代码,使它不依赖于全局变量的共享状态。

你可以通过__declspec(thread)声明STRCT来让它工作,这将使用线程本地存储,这样每个线程都可以获得自己的变量副本。然而,这对于每个非托管线程来说都是唯一的,并且不能保证托管线程和非托管线程之间存在一对一的映射。

更好的解决方案是完全摆脱共享状态。您可以通过在setClue中分配SRCH_STRUCT并返回该指针来实现这一点。然后每次调用srchString都会将SRCH_STRUCT指针作为参数。VB。Net代码只需要像对待IntPtr一样对待这个结构体,它不需要知道任何关于SRCH_STRUCT的定义。注意,您还需要向DLL中添加一个新函数来释放已分配的SRCH_STRUCT

最新更新