Access violation when using DLL

I have a DLL to control a mobil printer but I get an access violation on 
FreeLibrary (nothing gets printed).
The debugger stops here in the Controls unit.
function DoControlMsg(ControlHandle: HWnd; var Message): Boolean;
var
  Control: TWinControl;
begin
  DoControlMsg := False;
  Control := FindControl(ControlHandle);
  if Control <> nil then
    with TMessage(Message) do
    begin
      Result := Control.Perform(Msg + CN_BASE, WParam, LParam);
      DoControlMsg := True;
    end;
end;

Here is the code:
Var
Bixolon: Thandle;
PrinterOpen: function(strOutPortName: PWChar; LTIMEOUT: INTEGER): Integer 
cdecl {$IFDEF WIN32} stdcall {$ENDIF};
PrinterClose: function: Integer cdecl  {$IFDEF WIN32} stdcall {$ENDIF};
PrintText: function(Data: string; Alignment: LongInt; Attribute: LongInt; 
TextSize: LongInt): Integer cdecl  {$IFDEF WIN32} stdcall {$ENDIF};
PrinterName: Array[0..200] of char;
begin
     StrPCopy(PrinterName,'BIXOLON SPP-R200');
     Bixolon := LoadLibrary('bxlx86win.dll');
     if Bixolon >= 32 then
        begin
             PrinterOpen := GetProcAddress(Bixolon, 'PrinterOpen');
             if addr(PrinterOpen) <> nil then
                PrinterOpen('BIXOLON SPP-R200',1000);
             PrintText := GetProcAddress(Bixolon, 'PrintText');
            if addr(PrinterText) <> nil then
               PrintText(' Hello World',1,1,1);
             PrinterClose := GetProcAddress(Bixolon, 'PrinterClose');
            if addr(PrinterClose) <> nil then
             PrinterClose;
        end
     else
     MessageDlg('Error: could not find bxlx86win.dll', mtError, [mbOk], 0);
        FreeLibrary(Bixolon);

I found the functions in a C header file, which I tried to convert with Dr. 
Bob headerconv. It converted them but they had to many errors, so I tried to 
convert just the ones I need.
Her are the function from the C header file.
BXLPTR_API long __cdecl PrinterOpen(LPCTSTR strOutPortName, long lTimeout = 
1000);
BXLPTR_API long __cdecl PrinterClose();
BXLPTR_API long __cdecl PrintText(LPCTSTR Data, long Alignment, long 
Attribute, long TextSize);

Unfortunatly this SDK only have C#, VB.Net and VC6 examples.
Thanks for any help,
Kim
0
Kim
10/30/2009 1:38:35 AM
embarcadero.delphi.nativeapi 1236 articles. 1 followers. Follow

8 Replies
1704 Views

Similar Articles

[PageSpeed] 49
Get it on Google Play
Get it on Apple App Store

Kim Jensen wrote:
> I have a DLL to control a mobil printer but I get an access violation on 
> FreeLibrary (nothing gets printed).
> The debugger stops here in the Controls unit.
> function DoControlMsg(ControlHandle: HWnd; var Message): Boolean;
> var
>   Control: TWinControl;
> begin
>   DoControlMsg := False;
>   Control := FindControl(ControlHandle);
>   if Control <> nil then
>     with TMessage(Message) do
>     begin
>       Result := Control.Perform(Msg + CN_BASE, WParam, LParam);
>       DoControlMsg := True;
>     end;
> end;
> 
> Here is the code:
> Var
> Bixolon: Thandle;
> PrinterOpen: function(strOutPortName: PWChar; LTIMEOUT: INTEGER): Integer 
> cdecl {$IFDEF WIN32} stdcall {$ENDIF};
> PrinterClose: function: Integer cdecl  {$IFDEF WIN32} stdcall {$ENDIF};
> PrintText: function(Data: string; Alignment: LongInt; Attribute: LongInt; 
> TextSize: LongInt): Integer cdecl  {$IFDEF WIN32} stdcall {$ENDIF};

"String" is never a valid type for use with C DLLs (and it's rarely a 
good idea for any DLLs at all). The first parameter for PrintText should 
be a pointer to a character, either PAnsiChar or PWideChar. It's 
impossible to tell which from the C declarations you posted below.

> PrinterName: Array[0..200] of char;
> begin
>      StrPCopy(PrinterName,'BIXOLON SPP-R200');

Please get in the habit of using StrPLCopy, specifying the number of 
characters available in the destination array.

>      Bixolon := LoadLibrary('bxlx86win.dll');
>      if Bixolon >= 32 then

What's with the magic number 32? The documentation for LoadLibrary says 
nothing about that. LoadLibrary returns zero on failure. All other 
numbers (including negative ones) are valid values.

>         begin
>              PrinterOpen := GetProcAddress(Bixolon, 'PrinterOpen');
>              if addr(PrinterOpen) <> nil then
>                 PrinterOpen('BIXOLON SPP-R200',1000);
>              PrintText := GetProcAddress(Bixolon, 'PrintText');
>             if addr(PrinterText) <> nil then
>                PrintText(' Hello World',1,1,1);
>              PrinterClose := GetProcAddress(Bixolon, 'PrinterClose');
>             if addr(PrinterClose) <> nil then
>              PrinterClose;
>         end
>      else
>      MessageDlg('Error: could not find bxlx86win.dll', mtError, [mbOk], 0);

Don't assume that failure to load a DLL is due to the inability to find 
the file. GetLastError will tell you why LoadLibrary failed.

>         FreeLibrary(Bixolon);

Only free the library if you managed to load it.

> I found the functions in a C header file, which I tried to convert with Dr. 
> Bob headerconv. It converted them but they had to many errors, so I tried to 
> convert just the ones I need.
> Her are the function from the C header file.
> BXLPTR_API long __cdecl PrinterOpen(LPCTSTR strOutPortName, long lTimeout = 
> 1000);
> BXLPTR_API long __cdecl PrinterClose();
> BXLPTR_API long __cdecl PrintText(LPCTSTR Data, long Alignment, long 
> Attribute, long TextSize);

Those declarations explicitly say they use the cdecl calling convention. 
Your Delphi declarations use stdcall. Get rid of the stdcall directives 
from your code.

There's something wrong with the C declarations, though. They use the 
"T" character types, which can change based on other compiler settings. 
Are you sure those are the *only* declarations available? There should 
be some that use types like LPCSTR or LPCWSTR instead.

> Unfortunatly this SDK only have C#, VB.Net and VC6 examples.

That should be plenty.

-- 
Rob
0
Rob
10/30/2009 2:06:58 AM
Hi Rob,

Thanks for taking the time, most of the stuff about DLL was found on Dr 
Bob's website.

>>      if Bixolon >= 32 then
>
> What's with the magic number 32? The documentation for LoadLibrary says
> nothing about that. LoadLibrary returns zero on failure. All other
> numbers (including negative ones) are valid values.

That is the example I found on DR Bob's website.


>> BXLPTR_API long __cdecl PrinterOpen(LPCTSTR strOutPortName, long lTimeout 
>> =
>> 1000);
> Those declarations explicitly say they use the cdecl calling convention.
> Your Delphi declarations use stdcall. Get rid of the stdcall directives
> from your code.

Then it should look like this?
PrinterOpen: function(strOutPortName: PWChar; LTIMEOUT: INTEGER): Integer 
cdecl;


> There's something wrong with the C declarations, though. They use the
> "T" character types, which can change based on other compiler settings.
> Are you sure those are the *only* declarations available? There should
> be some that use types like LPCSTR or LPCWSTR instead.

The same one from a C# public class
[DllImport(BXLDIR, SetLastError = true, EntryPoint = "PrinterOpen")]
        public static extern Int32 PrinterOpen(string strPort, Int32 
lTimeout);

The same from a VB.Net
<DllImport(BXLDIR, EntryPoint:="PrinterOpen")> _
    Public Function PrinterOpen(ByVal strOutPortName As String, ByVal 
lTimeout As Int32) As Int32
    End Function

Thanks,
Kim
0
Kim
10/30/2009 9:21:12 PM
Kim Jensen wrote :
> Hi Rob,

>> What's with the magic number 32? The documentation for LoadLibrary says
>> nothing about that. LoadLibrary returns zero on failure. All other
>> numbers (including negative ones) are valid values.
>
> That is the example I found on DR Bob's website.

The 16 bit API LoadLibrary returned an error smaller than HINSTANCE_ERROR (32). 
Maybe that was an older example.

Regards.
0
Sertac
10/31/2009 12:04:13 AM
Rob Kennedy wrote:

> >      Bixolon := LoadLibrary('bxlx86win.dll');
> >      if Bixolon >= 32 then
> 
> What's with the magic number 32? The documentation for LoadLibrary
> says nothing about that. LoadLibrary returns zero on failure. All
> other numbers (including negative ones) are valid values.

That's true, but I have seen this number 32 before. ISTR that it had a
meaning once, but can't find any info on it anymore.

Oh wait, I found that the BPW7 help says that values below 32 are error
values. So that magical number used to have importance on Win3.x
-- 
Rudy Velthuis (TeamB)        http://www.teamb.com

"Silence is argument carried out by other means."
 -- Ernesto "Che" Guevara (1928-1967)
0
Rudy
10/31/2009 11:40:55 AM
Ok got some function to work, now I just need to translate the rest of the 
..H file.

How will I translate this to Delphi or do I need the first two?

#pragma comment (lib, "bxlx86win.lib")

#define BXLPTR_API __declspec(dllimport)

BXLPTR_API long __cdecl PrinterClose();

Thanks,
Kim
0
Kim
11/3/2009 2:07:16 AM
Kim Jensen wrote:
> Ok got some function to work, now I just need to translate the rest of the 
> .H file.
> 
> How will I translate this to Delphi or do I need the first two?
> 
> #pragma comment (lib, "bxlx86win.lib")

That tells the linker that the given lib file should be linked into the 
final program, so it will be searched for not-yet-resolved external 
functions. Delphi does things differently. In Delphi, each external 
function gets associated with exactly one DLL, and there are no lib 
files involved.

> #define BXLPTR_API __declspec(dllimport)
> 
> BXLPTR_API long __cdecl PrinterClose();

function PrinterClose: LongInt; cdecl; external 'name-of-dll';

-- 
Rob
0
Rob
11/5/2009 8:38:03 AM
Kim Jensen wrote:

> Ok got some function to work, now I just need to translate the rest
> of the .H file.
> 
> How will I translate this to Delphi or do I need the first two?
> 
> #pragma comment (lib, "bxlx86win.lib")

No need for that in Delphi. Probably very non-standard anyway.
> 
> #define BXLPTR_API __declspec(dllimport)

Not required in Delphi.
> 
> BXLPTR_API long __cdecl PrinterClose();


  function PrinterClose: Longint; cdecl;
    external 'somename.dll' name 'PrinterClose';


-- 
Rudy Velthuis (TeamB)        http://www.teamb.com

"Distrust all in whom the impulse to punish is powerful."
 -- Nietzsche
0
Rudy
11/5/2009 5:49:16 PM
Thanks, to every one I got the DLL to work.

Kim
0
Kim
11/9/2009 5:47:57 PM
Reply:

Similar Artilces:

Using DLL -- Access Violation
HI everyone, i don't know where to post this problem so I put it here because it deals with a DLL that connects to a web service. I'm writing a DLL that connects to a webService and that implements some business logic with the data it captures from the web service. This DLL has to be used by other languages. The problem I have is that when I try to use the DLL with other languages I get an access violation. I'm writing the DLL with Delphi 2009 Professional Edition and I try to use the DLL with a program writed in Delphi 6 professional. Why when I try to call a function from ...

Access violation when using COM interop DLL
Hi, In my application (VCL forms C++ application), I am using COM interop DLL built in C#.net. I have set ComVisiblle attribute to my classes and interfaces in C# project. In my VCL application I imported these class type and interfaces by importing type library (TLB file). With this I am able to call methods from .net assembly. However sometime I am getting access violation errors. See below call stack. Could you please help me to identify what could be the problem. Function Arg 1 Arg 2 Arg 3 Arg 4 Source clr!RCW::ReleaseAllInterfaces+70 81188c0d 09befc9...

Access Violation Delphi XE7 using IBSQL or IB
Hi, I'm getting an access violation opening a TIBSQL or TIBQuery after upgrading my project to XE 7. The error is being raised in procedure TIBSQL.Prepare and is happening on the following line: bt := Database.Encoding.GetBytes(FProcessedSQL.Text + #0); I'm guessing there's a new property added to one of the IBX components that's not being set. Any ideas? Thanks, Dan Palley Dan Palley wrote: > Hi, I'm getting an access violation opening a TIBSQL or TIBQuery after upgrading my project to XE 7. The error is being raised in procedure TIBSQL.Prepare...

Use of TBCDField in Aggregate causes access violation in Delphi XE7
I have just converted my application from Delphi 7 to Delphi XE7. To get the application to compile clean was surprisingly easy. However, I am now getting access violations in a number of areas. I have narrowed down the problem to the use of a TBCDField in a aggregate of a ClientDataset. The back end of my application is SQL Server 2008 R2. There are a number of fields in the database with a datatype of 'money'. When you bring in a SQL Server DataType of Money into a dataset (query or clientdataset) Delphi assigns the field a datatype of TBCDField. When I use a field with a ...

Use of TBCDField in Aggregate causes access violation in Delphi XE7
I have just converted my application from Delphi 7 to Delphi XE7. To get the application to compile clean was surprisingly easy. However, I am now getting access violations in a number of areas. I have narrowed down the problem to the use of a TBCDField in a aggregate of a ClientDataset. The back end of my application is SQL Server 2008 R2. There are a number of fields in the database with a datatype of 'money'. When you bring in a SQL Server DataType of Money into a dataset (query or clientdataset) Delphi assigns the field a datatype of TBCDField. When I use a field with a ...

Delphi XE Access violation in module 'dbxfb.dll'
Hi to all, I'm testing dbExpress and some times I get an access violation with this code: {code} function TForm1.GetBlobText(id: Integer): String; begin Result := ''; if (id > 0) then try if not SQLConnection1.Connected then SQLConnection1.Connected := True; SQLQuery1.Close; SQLQuery1.Sql.Text := Format('SELECT id, somefield, txt_field FROM my_table WHERE id = %d', [id]); SQLQuery1.Open; Result := SQLQuery1.FieldByName('txt_field').AsString; except ...

Delphi XE Access violation in module 'dbxfb.dll' #2
Hi to all. I'm forced to migrate a Delphi 2007 application to Delphi XE using DbExpress and the dbxfb.dll driver. I had to make a trick for loading Blob fields into a TRichEdit. I got enforced to write this code: {code} procedure TForm1.LoadMemo(id: Integer); var I: Integer; strText: AnsiString; myStream: TMemoryStream; begin SQLQuery1.Close; SQLQuery1.Sql.Text := 'SELECT id, txt_field FROM my_table WHERE id = ' + IntToStr(id); SQLQuery1.Open; strText := SQLQuery1.FieldByName('txt_field').AsString; myStream := TMemoryStream...

delphi Win32 using delphi .NET dll
Hi, I'm trying to use a delphi.NET dll in delphi.WIN32. I am currently using CodeGear Delphi 2007 with version2(base version) of .NET I can get the dll to import into the WIN32 application the only problem is when i include things such as: "using Classes,DateUtils, SysUtils" in the .NET dll the win32 application will instantly hang when any of the dll functions are called. Any help would be great thanks. Also I have tried this example and it also crashes for me? http://cc.embarcadero.com/Item/22688 -Braden I also found this.. "The problem is that, wehn you instal...

msado15.dll,ntdll.dll Access Violation in XP (sp3)
Hi every one.. Im try something.. I coded a little exe on win 7 64 bit with XE2... one form one adoquery one adoconnection one datasource one dbgrid my query has got one parameters... I create parameters by code. my code block: adoquery1.Close; adoquery1.SQL.Clear; adoquery1.Parameters.Clear; adoquery1.Parameters.CreateParameter('pr_param1',ftinteger,pdInput,0,0); showmessage(adoquery1.Parameters[0].Name); adoquery1.SQL.ADD('SELECT (SELECT table1.field1 FROM table1 WHERE table1.OPKODU=table2.OPERASYONKODU) AS OPISIM,* FROM table2 WHERE INCKEYNO=:pr_param1)...

Trying to call a .DLL from Delphi XE (used to work with Delphi 6 :-) )
Hi everyone, I have a problem where perhaps some one could help point me in the right direction. In Delphi 6 I used a stand alone package to train a neural netowrk,. The trained neural network was stored as a .DEF file. The standalone software provided a .DLL and Delphi code to call the network and get the prediced values from your sw. (The .DLL was created in 2002 and apparently is 32 bit.) I have'nt used it for years but am now coming back to it.... I now use Delphi XE on Windows 7 (32 bit) The old .exe's I had compiled from that time work fine. However in Delphi XE ...

To use or not to use Delphi
Sadly, it seems to me that there is a sort of race between the two threads, for and against using Delphi in new projects, with more or less the same users posting in both threads. Arguments are fiercely debated in both camps. Borland had their own vision. As a community, now that Delphi has changed ownership I believe we should try to be more consistent, more clear, and more articulate in what we expect from Embercadero in terms of Delphi. We can contribute to keeping Delphi alive and moving in the right direction. "Laurent Cocea" schrieb: > Sadly, it seems to me that there ...

How to Track Access Violation in a DLL
I am using CB2009 and CB6.0. I am looking for guidance on how to setup my program and dlls so I can track an Access Violations in a dll. Right now I do not know any good way to do this. Can anyone recommend an Embarcadero article or provide personal advice on the best way to setup my EXE and DLLs for tracking Access Violations in a dll. Thanks Patrick M. <patrick mikula> wrote in message news:164379@forums.codegear.com... > I am looking for guidance on how to setup my program and dlls so I can > track an Access Violations in a dll. Right now I do not know any good ...

access violation dcc90.dll
1) D7 Perso : using line command parameter -hm when running the IDE will show the allocate blocs in the IDE title... Is there the same with D2005 ? 2) D2005 + a program running perfectly under D7 (no memory leaks) : after running (run + closing by F4 my app) from the 2005 IDE, this one crashes with an access violation in dcc90.dll ! Running (run + closing by F4 my app) the executable from Windows XP (outside the 2005 IDE) causes no messages... My app uses threads, that are correctly terminated at closing the program. What is dcc90.dll ? DH "David HAROUCHE&quo...

Access Violation in NTDll.dll
Has anyone run across this error ? (Access violation in Ntdll.dll). I have a three teir application written in Delphi5. The app server piece normally uses ASE against a third teir database machine. For the purposes of portability and testing, we have redirected that app server at an ASA database on the local machine. Once I got the latest EBF's applied (6.03.xxxx) everything seems to work fine. The problem that I am having though is when the application server's application closes down (i.e. the last user disconnects) I get the "Access Violation in NtDll.Dll"...

Web resources about - Access violation when using DLL - embarcadero.delphi.nativeapi

CP violation - Wikipedia, the free encyclopedia
In particle physics , CP violation is a violation of the postulated CP-symmetry : the combination of C-symmetry ( charge conjugation symmetry) ...

James-O'Keefe-Parole-Violations - Flickr - Photo Sharing!
James O'Keefe, liar and scam artist, has been spotted in NYC in violation of his parole in Lousiana.

Civil Rights Violation on Video Pledge and Invocation - YouTube
Civil Rights Violation on Video Pledge and Invocation - YouTube

UAE Police issue more than 25,000 traffic violations involving lorries in Q1 of 2014 - The National
Police said several people have been killed in accidents involving lorries so far this year.

Russia closes 12 McDonald's restaurants over hygiene violations
Russia has temporarily closed 12 branches of McDonald's on health grounds and is carrying out more than 100 inspections, the US fast food chain ...

CFMEU implicated in threats against Melbourne contractor and site entry violations
Victoria's powerful construction union allegedly told a company it is on a &quot;hit list&quot; and would suffer industrial strife as payback ...

Report alleges labour violations at Apple supplier in China
Report claims dangerous conditions, labour violations at another Apple plant.

Hints of Eurovision vote violation against Russia
The head of Azerbaijan's state broadcaster has questioned the vote tally in the Eurovision Song Contest where it embarrassingly gave "nul points" ...

Nick Kyrgios issued code violation at Japan Open - The Courier-Mail Search Search
NICK Kyrgios has hit out at the Australian media following his loss to Frenchman Benoit Paire at the Japan Open on the weekend.

Nick Kyrgios issued code violation at Japan Open
NICK Kyrgios has hit out at the Australian media following his loss to Frenchman Benoit Paire at the Japan Open on the weekend.

Resources last updated: 2/3/2016 11:40:45 AM